Now, let's understand the complete code first. The comments explain each relevant step within the code:
function suggestZipCodes() {
//defined possible ZipCode
ZipCodes = [
{ name: '94102' },
{ name: '94103' },
{ name: '94104' },
{ name: '94105' },
{ name: '94107' },
{ name: '94108' }
];
var OnZipCodekeyPress = function (fld) {
var ZipCodetxt = Xrm.Page.getControl
("address1_postalcode").getValue();
resultSet = {
results: new Array(),
commands: {
id: "ZipCodecmd",
label: "Search in Bing",
action: function () {
window.open("http://bing.com"); //Open Bing URL
}
}
};
var ZipCodetxtLowerCase = ZipCodetxt.toLowerCase();
for (i = 0; i < ZipCodes.length; i++) {
if (ZipCodetxtLowerCase ===
ZipCodes[i].name.substring(0,
ZipCodetxtLowerCase.length).toLowerCase()) {
resultSet.results.push({
id: i,
fields: [ZipCodes[i].name]
});
}
if (resultSet.results.length >= 10) {
break;
}
}
if (resultSet.results.length > 0) {
//Show Auto Complete
fld.getEventSource().showAutoComplete(resultSet);
}
else {
//Hide Auto Complete
fld.getEventSource().hideAutoComplete();
}
};
Xrm.Page.getControl("address1_postalcode").addOnKeyPress
(OnZipCodekeyPress);
}
Now, let's look at the steps to be performed after completing the code:
- Navigate to Settings | Customization | Customize the System and select Web Resources. Click New:
- Name the web resource as zipCodeAutoComplete. Select Type as Script(JScript) and paste the preceding code in the Text Editor link:
- On clicking the Text Editor button, you will be able to paste the code into it:
- Click OK. On the main screen, click Save and Publish. Next, navigate to Contact entity | Forms. Open the Contact main form by double-clicking on it:
- Click on the Form Properties ribbon button on the form editor:
- Attach the WebResource script (created earlier to form libraries) by clicking Form Properties and attach the method name to the On Load event handler:
- Click OK. Then click on Save and Publish to publish the form.
- Now, as soon as any employee types in to the ZIP code field, he or she is presented with options for assistance, diminishing the chances of error:
This is how we can get autocomplete selection for ZIP codes in our forms.