Archive

Posts Tagged ‘JQuery’

Web Development – Useful jQuery Syntax’s

In this article, I am compiling the useful jQuery syntax’s which comes handy during your Dynmaics/ADX portal development or any other web development.

Prerequisite

  • Add jQuery library to your web page using <script> tag.
  • You can get the jQuery CDN here

Get Operations:

  • Get HTML element by Id

$(“#HTMLelementId“)

  • Get element by Class name

$(“.ClassName“)

  • Get element by ‘partial’ Id name.
    • As an example, if you want to get a Checkbox control which has ID ‘myChkBox‘, you can either get the element using full id with $(“#myChkBox”) or use partial id $(“[id$=’ChkBox‘]”).

$(“[id$=’PartialId‘]”)

  • Get Value

$(“#HTMLelementId“).val()

  • Get selected drop down text

$(“#DropdownId option:selected”).text()

Set Operations:

  • Set Text box

$(“#HTMLelementId“).val(“Hello World”);

  • Set Checkbox

$(“#checkboxId“).prop(“checked”, true); //true is checked; false is unchecked.

Add or Remove CSS Class

  • $(“#HTMLelementId“).addClass(“YourClassName“); // Add Class
  • $(“#HTMLelementId“).removeClass(“YourClassName“); // Remove Class

Hide/Show Element

  • Hide element

$(“#HTMLelementId“).hide();

  • To hide Parent
    • This is useful to hide a control along with Label.

$(“#HTMLelementId“).parent().hide()

  • Show element

$(“#HTMLelementId“).show();

Check if element exists on page

if ($(“#HTMLelementId“).length > 0){}

Iteration syntax

  • Loop through all Radio boxes which set to False.

$(“input[id][type=’radio’][value=’0′]”).each(function () {
var radioBox = this;
});

Attach events to HTML elements

  • To add ‘keypress’ event to Text box

$(“#HTMLelementId“).on(“keypress”, keyPressHandler);

function keyPressHandler(){
// Read the textbox value
var controlValue = this.val();
}

Remove event handler

  • To remove ‘onChange’ event from a control use ‘unbind’ method.

$(“#dropDownID“).unbind(“change”);

Trigger event

  • To trigger button ‘Click’ event

$(“#ButtonId“).click();

Remove option from Drop down:

  • Below script, removes ‘Mango’ from the Drop down control.

jQuery(“#dropdownId option:contains(‘Mango’)”).remove();

Read Query String Parameter

  • To read ‘country’ param value from current URL http://helloworld?country=India, call getParamValue(‘country’)
  • Function will return false, if no matching param found.

function getParamValue(paramName) {
var results = new RegExp(‘[\?&]’ + paramName + ‘=([^&#]*)’)
.exec(window.location.search);

return (results !== null) ? results[1] || 0 : false;
}

Get/Set elements in IFrame

  • To Get or Set the values of elements in IFrame, below is the syntax.

$(“#YourIframeID“).contents().find(‘#txtBoxId‘).val(); // Get the value

$(“#YourIframeID“).contents().find(‘#txtBoxId‘).val(“Hello World”); // Set the value

  • To access IFrame with in another IFrame

$(“#Iframe1ID“).contents().find(“#Iframe2ID“).contents().find(‘#txtBoxId‘).val(“Hello World”);

Create a new element:

  • Below is the snippet to create HTML button and add that next to an existing HTML element.

$(‘<input type=”button” id=”newBtn” class=”Your class name” value=”My New Button”/>’).insertAfter($(“#existingHTMLElementId“));
$(“#newBtn”).click(function () {

// Write your onclick script here
});

File Upload Control – Clear selected file:

  • We cannot clear the selected file from ‘File Upload’ control, by using $(“#fileuploadcontrolID”).val(“”).
  • We have to create a new element and replace the existing one.
  • Below statement clones the existing element, with blank file name and replaces the existing element.

$(“#fileuploadcontrolID“).replaceWith($(“#fileuploadcontrolID“).val(”).clone(true));

🙂

Advertisement

Dynamics Portals – Web Templates – ‘$ is not defined’ Error

Other day, I was getting ‘$ is not defined’ script error during my ‘Web Template’ load.

Portal_$_1

From the error, its clear that jQuery file reference was missing in Web Template.

The Web Template has a HTML with Liquid Template and script using jQuery and was rendering with no issues an hour ago and there were no changes made to the Web Template content.

Reason and Fix:

  • ‘Use Website Header and Footer’ field was unchecked in ‘Page Template’ which was causing the issue.

Portal_$_2

  • jQuery file would be implicitly available to the ‘Web Template’ when ‘Use Website Header and Footer’ field is checked on ‘Page Template’.
  • Save the Page Template
  • Clear the portal Cache and issue should be fixed.

🙂

 

 

 

Object doesn’t support this property or method XMLHttpRequest error – FIX

Hi,

I was getting “object doesn’t support this property or method jquery” error when I was initializing

var request = new XMLHttpRequest();

Reason :-

  • This is a problem with Internet Explorer browser (ActiveX to be precise)

Fix :-

  • If the browser is detected as Internet Explorer, load ActiveX instead of XMLHttpRequest
  • Below condition check would solve the problem

var request;

if ($.browser.msie) {

request = new ActiveXObject(“Microsoft.XMLHTTP”);

} else {

request = new XMLHttpRequest();

}

🙂

Retrieve multiple records using OData & JQuery in CRM 2011

March 26, 2012 5 comments

Hi,

Below are the Jscript functions to retrieve multiple records using OData & JQuery.

function retrieveMultiple(odataSetName, select, filter, successCallback) {

var serverUrl = Xrm.Page.context.getServerUrl();

var ODATA_ENDPOINT = “/XRMServices/2011/OrganizationData.svc”;

var odataUri = serverUrl + ODATA_ENDPOINT + “/” + odataSetName + “?”;

if (select) {

odataUri += “$select=” + select + “&”;

}

if (filter) {

odataUri += “$filter=” + filter;

}

//Asynchronous AJAX function to Retrieve CRM records using OData

$.ajax({

type: “GET”,

contentType: “application/json; charset=utf-8”,

datatype: “json”,

url: odataUri,

beforeSend: function (XMLHttpRequest) {

//Specifying this header ensures that the results will be returned as JSON.

XMLHttpRequest.setRequestHeader(“Accept”, “application/json”);

},

success: function (data, textStatus, XmlHttpRequest) {

if (successCallback) {

if (data && data.d && data.d.results) {

successCallback(data.d.results, textStatus, XmlHttpRequest);

}

else if (data && data.d) {

successCallback(data.d, textStatus, XmlHttpRequest);

}

else {

successCallback(data, textStatus, XmlHttpRequest);

}

}

},

error: function (XmlHttpRequest, textStatus, errorThrown) {

if (XmlHttpRequest && XmlHttpRequest.responseText) {

alert(“Error while retrieval ; Error – ” + XmlHttpRequest.responseText);

}

}

});

}

function readRecordsOnSuccess(data, textStatus, XmlHttpRequest) {

// Loop through the retrieved records

for (var indx = 0; indx < data.length; indx++) {

alert(“Name – ” + data[indx].name);

}

}

  • Copy & Paste above methods to a new .jscript file
  • Replace double quotes(“) symbols with your keyboard double quotes
  • Add the new .jscript file as web resource to CRM application
  • Add “Jquery” & json” helper classes as web resources

How do I call this method :-

  • In my sample below, I will show you how to read “Contacts” for an “Account”

function retrieveContactsByAccountId() {

// Pass ‘Contact’ set name since we are reading Contacts

var oDataSetName = “ContactSet”;

// Column names of ‘Contact’ (Pass * to read all columns)

var columns = “FirstName,LastName”;

// Read Account Guid

var accountId = Xrm.Page.data.entity.getId()

// Prepare filter

var filter = “AccountId/Id eq guid'” + accountId + “‘”;

retrieveMultiple(oDataSetName, columns, filter, readRecordsOnSuccess);

}

Note :- Import “ODataQueryDesigner” solution to prepare the Filters easily.

Hope it helps 🙂

Deleting a record using OData & JQuery in CRM 2011

February 20, 2012 Leave a comment

Hi,

Below is the script to delete record using OData & JScript

 

function deleteRecord(id, odataSetName) {

// Get Server URL

var serverUrl = Xrm.Page.context.getServerUrl();

//The OData end-point

var ODATA_ENDPOINT = “/XRMServices/2011/OrganizationData.svc”;

//Asynchronous AJAX function to Delete a CRM record using OData

$.ajax({

type: “POST”,

contentType: “application/json; charset=utf-8”,

datatype: “json”,

url: serverUrl + ODATA_ENDPOINT + “/” + odataSetName + “(guid'” + id + “‘)”,

beforeSend: function (XMLHttpRequest) {

//Specifying this header ensures that the results will be returned as JSON.

XMLHttpRequest.setRequestHeader(“Accept”, “application/json”);

//Specify the HTTP method DELETE to perform a delete operation.

XMLHttpRequest.setRequestHeader(“X-HTTP-Method”, “DELETE”);

},

success: function (data, textStatus, XmlHttpRequest) {

alert(“Record deleted successfully!!!!”);

},

error: function (XmlHttpRequest, textStatus, errorThrown) {

alert(“Error while deletion – “+errorThrown);

}

});

}

 

How Do I call this method :-

    • To delete a “Account” record  set account id & Odata set name and call the above method

var accountId = {}; //Set Account GUID

var odataSeName = “AccountSet”;

deleteRecord(accountId, odataSeName);

 

Hope it helps 🙂