Return to Snippet

Revision: 58162
at July 7, 2012 01:54 by evshell18


Updated Code
///<reference path="XrmPage-vsdoc.js"/>
///<reference path="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1-vsdoc.js"/>

/*
- This code originally written in June 2011 by Bill Caldwell (dynamicscrmdenver.com) from McGladrey
- This code was modified in October 2011 by Bill C to consume the latest yahoo geocode services
- This code was modified on 5/25/2012 by Bill C to provide international postal code functionality
- This code was modified on 6/27/2012 by Evan Kaiser to make the country field parameter optional, 
to allow the choice of using full or abbreviated state name, as well as to provide support for multiple 
browsers using the JQuery library.
- NOTE: Code requires that the page using it first includes a reference to JQuery and JSON. Here is a link to a
managed CRM solution containing JQuery and JSON2 Web Resources that you can include on your CRM forms:
https://skydrive.live.com/embedicon.aspx/.Public/jQueryCRM2011_1_6_0_0_managed.zip?cid=0f98a78f1c3c4457&sc=documents

o Parameters:
-- abbreviateState defaults to false, so unless it is specifically passed in as "true", it will use the full state name
-- The user is not required to enter the country (will default to US)
-- usage: ZipCodeLookup("address1_postalcode", "address1_city", "address1_stateorprovince", true/false, "address1_country");
*/
var _cityTypeName = "Town";
var _stateTypeName = "State";
var _cityDdl;
var _savedCity;
var _savedState;
var _cityFieldName;
var _stateFieldName;
var _heldState;
var _heldStateCode;
var _isDropdown;
var _matchFound;

function ZipCodeLookup(zipFieldName, cityFieldName, stateFieldName, abbreviateState, countryFieldName) {

    _cityFieldName = cityFieldName;
    _stateFieldName = stateFieldName;
    _savedCity = Xrm.Page.getAttribute(_cityFieldName).getValue();
    _savedState = Xrm.Page.getAttribute(_stateFieldName).getValue();
    Xrm.Page.getAttribute(_cityFieldName).setValue("Localizing...");
    Xrm.Page.getAttribute(_stateFieldName).setValue(null);
    _isDropdown = false;

    if (arguments.length < 4) {
        abbreviateState = false;
    }

    // Verify that the field is valid
    var zip = Xrm.Page.getAttribute(zipFieldName).getValue();
    if (zip != null) {

        // define Yahoo YQL query
        var wsql = 'select * from geo.places where text="' + zip + '"';

        // pass country 
        var country = null;
        if (arguments.length > 4 && countryFieldName.length > 0) {
            country = Xrm.Page.getAttribute(countryFieldName).getValue();
        }
        if (country == null) {
            country = "United States";
        }
        wsql = wsql + ' and country="' + country + '"';

        // get url to Yahoo YQL service 
        var yqlUrl = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent(wsql) + '&format=json&callback=?';

        _matchFound = false;
        setTimeout(ResetLocation, 5000);
        $.getJSON(yqlUrl, function (r) {

            var city;
            if (r.query.count == 1) {

                var node;
                for (key in r.query.results.place) {

                    node = r.query.results.place[key];
                    if (node && node.type && node.type == _cityTypeName) {
                        city = node.content;
                    }
                    else if (node && node.type && node.type == _stateTypeName) {
                        _heldState = node.content;
                        if (abbreviateState) {
                            _heldState = node.code.slice(-2);
                        }
                    }

                }

                if (city != null && city.length > 0) {
                    Xrm.Page.getAttribute(_cityFieldName).setValue(city);
                    _matchFound = true;
                    _savedCity = city;
                    SetState();
                }
                else {
                    BuildCityDropdown(r.query.results.place.woeid, _cityFieldName);
                }

            }
            else {
                alert("ZipCode cannot be found");
                // If zip code is not found, restore the original values
                Xrm.Page.getAttribute(_cityFieldName).setValue(_savedCity);
                Xrm.Page.getAttribute(_stateFieldName).setValue(_savedState);
            }
        });
    }
    else {
        // If zip code is not entered, restore the original values
        Xrm.Page.getAttribute(_cityFieldName).setValue(_savedCity);
        Xrm.Page.getAttribute(_stateFieldName).setValue(_savedState);
    }
}

function ResetLocation() {
    if (!_matchFound) {
        Xrm.Page.getAttribute(_cityFieldName).setValue(_savedCity);
        Xrm.Page.getAttribute(_stateFieldName).setValue(_savedState);
    }
}

function SetState() {
    var stateAttribute = Xrm.Page.getAttribute(_stateFieldName);
    if (stateAttribute.getAttributeType() == "optionset") {
        var options = stateAttribute.getOptions();
        for (var i = 0; i < options.length; i++) {
            if (options[i].text == _heldState) {
                stateAttribute.setValue(options[i].value);
                _savedState = options[i].value;
            }
        }
    }
    else {
        stateAttribute.setValue(_heldState);
        _savedState = _heldState;
    }
}

function BuildCityDropdown(woeid, _cityFieldName) {

    if (woeid != null && woeid.length > 0) {

        // define Yahoo YQL query for child places
        var wsql = "select * from geo.places.children where parent_woeid=" + woeid;

        // get url to Yahoo YQL service 
        var yqlUrl = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent(wsql) + '&format=json&callback=?';

        $.getJSON(yqlUrl, function (r) {

            if (r.query.count > 0) {
                _cityDdl = $("#" + _cityFieldName);
                _cityDdl.MakeDynamicDropDown();
                _cityDdl.DynamicDropDown.SetDefaultCss( 
                {
                    "background-color" : "Black",
                    "border-radius" : "100px",
                    "width" : $("#" + _cityFieldName).css("width"),
                    "padding" : "10px"
                });
                _cityDdl.DynamicDropDown.SetDefaultItemCss( 
                {
                    "background-color" : "White",
                    "border" : "2px solid #CCC"
                });
                _cityDdl.DynamicDropDown.SetDefaultItemHoverCss( 
                {
                    "background-color" : "#CCC",
                    "border" : "2px solid #333"
                });
                _cityDdl.DynamicDropDown.CreateHeader("Select a City...", 
                {
                    "font-weight" : "bold",
                    "font-style" : "italic"
                });

                _cityDdl.DynamicDropDown.Clear();
                var place;
                for (var i = 0; i < r.query.count; i++) {
                    place = r.query.results.place[i];

                    var node;
                    var innerDiv;
                    for (key in place) {
                        node = place[key];
                        if (node && node.type && node.type == _cityTypeName) {
                            _cityDdl.DynamicDropDown.AddItem(node.content, node.content);
                        }
                    }
                }

                _cityDdl.DynamicDropDown.bind("itemselected", function () {
                    Xrm.Page.getAttribute(_cityFieldName).setValue(_cityDdl.DynamicDropDown.SelectedText());
                    _matchFound = true;
                    SetState();
                    _cityDdl.DynamicDropDown.Close(300);
                });

                _cityDdl.DynamicDropDown.Open(300);
            }
            else {
                alert("Valid city cannot be found");
                Xrm.Page.getAttribute(_cityFieldName).setValue(_savedCity);
                Xrm.Page.getAttribute(_stateFieldName).setValue(_savedState);
            }
        });

    }
}

$(document).bind('click', function (event) {
    if (_cityDdl && _cityDdl.DynamicDropDown.IsOpen() && _cityDdl.DynamicDropDown.TargetIsThis(event.target.id)) {
        Xrm.Page.getAttribute(_cityFieldName).setValue(_savedCity);
        Xrm.Page.getAttribute(_stateFieldName).setValue(_savedState);
        _cityDdl.DynamicDropDown.Close(300);
    }
});

;(function ($) {
    var DynamicDropDown = function () {
        var _ddKey = "dyndd_";
        var _background;
        var _obj;
        var _spanDiv;
        var _defaultMap;
        var _defaultHoverMap;
        var _items;
        var _selectedIndex;
        var _selectedValue;
        var _selectedText;
        var _isDropdownOpen;
        
        /*********************** Events ***********************/
        
        var onitemselected = null;

        /*********************** Constructor ***********************/

        this.Create = function () {
            _obj = $('<div id="' + _ddKey + 'Body"></div>');
            _obj.css({
                'display' : 'none',
                'position' : 'absolute',
                'top' : '0px',
                'left' : '0px',
                'z-index' : '1001'
            });
            
            _background = $('<div id="' + _ddKey + 'bg"></div>');
            _background.css({
                'display' : 'none',
                'background-color' : '#000',
                'opacity': '0.8',
                'filter' : 'alpha(opacity=80)',
                'position' : 'absolute',
                'top' : '0px',
                'left' : '0px',
                'min-width' : '100%',
                'min-height' : '100%',
                'width' : '100%',
                'height' : '100%',
                'z-index' : '1000'
            });

            $(document.body).append(_obj);
            $(document.body).append(_background);

            _obj.bind('click', function (event) {
                if (event.target.id.indexOf(_ddKey + "Item") > -1) {
                    _selectedIndex = parseInt(event.target.id.replace(_ddKey + "Item", ""));
                    if (!isNaN(_selectedIndex)) {
                        _selectedValue = _items[_selectedIndex].value;
                        _selectedText = _items[_selectedIndex].text;
                        onitemselected();
                    }
                }
            });

            _items = [];
            return _obj;
        };
        
        /*********************** Public Methods ***********************/

        this.SetDefaultCss = function (cssMap) {
            _obj.css(cssMap);
        };

        this.SetDefaultItemCss = function (cssMap) {
            _defaultMap = cssMap;
        };

        this.SetDefaultItemHoverCss = function (cssMap) {
            _defaultHoverMap = cssMap;
        };

        this.CreateHeader = function (text, cssMap) {
            _spanDiv = $('<div id="' + _ddKey + 'Header"><span>' + text + '</span></div>');
            appendDiv(_spanDiv, cssMap);
        };

        this.AddItem = function (value, text, cssMap) {
            var itemCount = _items.length;
            _items[itemCount] = { value : value, text : text };

            var innerDiv = $('<div id="' + _ddKey + 'Item' + itemCount + '">' + text + '</div>');
            innerDiv.mouseover(function () {
                $(this).css(_defaultHoverMap);
            });
            appendDiv(innerDiv, cssMap);
        };

        this.Open = function (speed) {
            var parent = window;
            _obj.css({
                "top": ((($(parent).height() - _obj.outerHeight()) / 2) + $(parent).scrollTop() + "px"),
                "left": ((($(parent).width() - _obj.outerWidth()) / 2) + $(parent).scrollLeft() + "px")
            });

            _background.fadeIn(speed);
            _obj.fadeIn(speed);
            _isDropdownOpen = true;
        };

        this.Close = function (speed) {
            _obj.fadeOut(speed);
            _background.fadeOut(speed);
            _isDropdownOpen = false;
        };

        this.IsOpen = function () {
            return _isDropdownOpen;
        };

        this.SelectedIndex = function () {
            return _selectedIndex;
        };

        this.SelectedValue = function () {
            return _selectedValue;
        };

        this.SelectedText = function () {
            return _selectedText;
        };

        this.Clear = function () {
            _obj.children().each(function (key, value) {
                if (value.id.indexOf(_ddKey + "Item") > -1) {
                    $(value).remove();
                }
            });
        };

        this.ClearSelected = function () {
            _selectedIndex = -1;
            _selectedValue = "";
            _selectedText = "";
        };

        this.TargetIsThis = function (targetId) {
            return (targetId.indexOf(_ddKey) > -1);
        };

        this.bind = function (event, handler) {
            if (event.toLowerCase() == "itemselected") {
                onitemselected = handler;
            }
        };
        
        /*********************** Private Methods ***********************/

        var appendDiv = function (div, cssMap) {
            var newMap = [];
            for (key in _defaultMap) {
                newMap[key] = _defaultMap[key];
            }
            for (key in cssMap) {
                newMap[key] = cssMap[key];
            }
            div.css(newMap);
            div.mouseout(function () {
                $(this).css(newMap);
            });
            _obj.append(div);
        };
                
    };

    $.fn.MakeDynamicDropDown = function () {
        // Return early if this element already has a plugin instance
        if (this.DynamicDropDown) return;

        // Store plugin object as a property on the element
        this.DynamicDropDown = new DynamicDropDown();
        this.DynamicDropDown.Create();
    };

})(jQuery);

Revision: 58161
at July 7, 2012 01:51 by evshell18


Updated Code
///<reference path="XrmPage-vsdoc.js"/>
///<reference path="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1-vsdoc.js"/>

/*
- This code originally written in June 2011 by Bill Caldwell (dynamicscrmdenver.com) from McGladrey
- This code was modified in October 2011 by Bill C to consume the latest yahoo geocode services
- This code was modified on 5/25/2012 by Bill C to provide international postal code functionality
- This code was modified on 6/27/2012 by Evan Kaiser to make the country field parameter optional, 
to allow the choice of using full or abbreviated state name, as well as to provide support for multiple 
browsers using the JQuery library.
- NOTE: Code requires that the page using it first includes a reference to JQuery and JSON. Here is a link to a
managed CRM solution containing JQuery and JSON2 Web Resources that you can include on your CRM forms:
https://skydrive.live.com/embedicon.aspx/.Public/jQueryCRM2011_1_6_0_0_managed.zip?cid=0f98a78f1c3c4457&sc=documents

o Parameters:
-- abbreviateState defaults to false, so unless it is specifically passed in as "true", it will use the full state name
-- The user is not required to enter the country (will default to US)
-- usage: pccd_ZipCodeLookup("address1_postalcode", "address1_city", "address1_stateorprovince", true/false, "address1_country");
*/
var _cityTypeName = "Town";
var _stateTypeName = "State";
var _cityDdl;
var _savedCity;
var _savedState;
var _cityFieldName;
var _stateFieldName;
var _heldState;
var _heldStateCode;
var _isDropdown;
var _matchFound;

function pccd_ZipCodeLookup(zipFieldName, cityFieldName, stateFieldName, abbreviateState, countryFieldName) {

    _cityFieldName = cityFieldName;
    _stateFieldName = stateFieldName;
    _savedCity = Xrm.Page.getAttribute(_cityFieldName).getValue();
    _savedState = Xrm.Page.getAttribute(_stateFieldName).getValue();
    Xrm.Page.getAttribute(_cityFieldName).setValue("Localizing...");
    Xrm.Page.getAttribute(_stateFieldName).setValue(null);
    _isDropdown = false;

    if (arguments.length < 4) {
        abbreviateState = false;
    }

    // Verify that the field is valid
    var zip = Xrm.Page.getAttribute(zipFieldName).getValue();
    if (zip != null) {

        // define Yahoo YQL query
        var wsql = 'select * from geo.places where text="' + zip + '"';

        // pass country 
        var country = null;
        if (arguments.length > 4 && countryFieldName.length > 0) {
            country = Xrm.Page.getAttribute(countryFieldName).getValue();
        }
        if (country == null) {
            country = "United States";
        }
        wsql = wsql + ' and country="' + country + '"';

        // get url to Yahoo YQL service 
        var yqlUrl = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent(wsql) + '&format=json&callback=?';

        _matchFound = false;
        setTimeout(pccd_ResetLocation, 5000);
        $.getJSON(yqlUrl, function (r) {

            var city;
            if (r.query.count == 1) {

                var node;
                for (key in r.query.results.place) {

                    node = r.query.results.place[key];
                    if (node && node.type && node.type == _cityTypeName) {
                        city = node.content;
                    }
                    else if (node && node.type && node.type == _stateTypeName) {
                        _heldState = node.content;
                        if (abbreviateState) {
                            _heldState = node.code.slice(-2);
                        }
                    }

                }

                if (city != null && city.length > 0) {
                    Xrm.Page.getAttribute(_cityFieldName).setValue(city);
                    _matchFound = true;
                    _savedCity = city;
                    pccd_SetState();
                }
                else {
                    pccd_BuildCityDropdown(r.query.results.place.woeid, _cityFieldName);
                }

            }
            else {
                alert("ZipCode cannot be found");
                // If zip code is not found, restore the original values
                Xrm.Page.getAttribute(_cityFieldName).setValue(_savedCity);
                Xrm.Page.getAttribute(_stateFieldName).setValue(_savedState);
            }
        });
    }
    else {
        // If zip code is not entered, restore the original values
        Xrm.Page.getAttribute(_cityFieldName).setValue(_savedCity);
        Xrm.Page.getAttribute(_stateFieldName).setValue(_savedState);
    }
}

function pccd_ResetLocation() {
    if (!_matchFound) {
        Xrm.Page.getAttribute(_cityFieldName).setValue(_savedCity);
        Xrm.Page.getAttribute(_stateFieldName).setValue(_savedState);
    }
}

function pccd_SetState() {
    var stateAttribute = Xrm.Page.getAttribute(_stateFieldName);
    if (stateAttribute.getAttributeType() == "optionset") {
        var options = stateAttribute.getOptions();
        for (var i = 0; i < options.length; i++) {
            if (options[i].text == _heldState) {
                stateAttribute.setValue(options[i].value);
                _savedState = options[i].value;
            }
        }
    }
    else {
        stateAttribute.setValue(_heldState);
        _savedState = _heldState;
    }
}

function pccd_BuildCityDropdown(woeid, _cityFieldName) {

    if (woeid != null && woeid.length > 0) {

        // define Yahoo YQL query for child places
        var wsql = "select * from geo.places.children where parent_woeid=" + woeid;

        // get url to Yahoo YQL service 
        var yqlUrl = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent(wsql) + '&format=json&callback=?';

        $.getJSON(yqlUrl, function (r) {

            if (r.query.count > 0) {
                _cityDdl = $("#" + _cityFieldName);
                _cityDdl.MakeDynamicDropDown();
                _cityDdl.DynamicDropDown.SetDefaultCss( 
                {
                    "background-color" : "Black",
                    "border-radius" : "100px",
                    "width" : $("#" + _cityFieldName).css("width"),
                    "padding" : "10px"
                });
                _cityDdl.DynamicDropDown.SetDefaultItemCss( 
                {
                    "background-color" : "White",
                    "border" : "2px solid #CCC"
                });
                _cityDdl.DynamicDropDown.SetDefaultItemHoverCss( 
                {
                    "background-color" : "#CCC",
                    "border" : "2px solid #333"
                });
                _cityDdl.DynamicDropDown.CreateHeader("Select a City...", 
                {
                    "font-weight" : "bold",
                    "font-style" : "italic"
                });

                _cityDdl.DynamicDropDown.Clear();
                var place;
                for (var i = 0; i < r.query.count; i++) {
                    place = r.query.results.place[i];

                    var node;
                    var innerDiv;
                    for (key in place) {
                        node = place[key];
                        if (node && node.type && node.type == _cityTypeName) {
                            _cityDdl.DynamicDropDown.AddItem(node.content, node.content);
                        }
                    }
                }

                _cityDdl.DynamicDropDown.bind("itemselected", function () {
                    Xrm.Page.getAttribute(_cityFieldName).setValue(_cityDdl.DynamicDropDown.SelectedText());
                    _matchFound = true;
                    pccd_SetState();
                    _cityDdl.DynamicDropDown.Close(300);
                });

                _cityDdl.DynamicDropDown.Open(300);
            }
            else {
                alert("Valid city cannot be found");
                Xrm.Page.getAttribute(_cityFieldName).setValue(_savedCity);
                Xrm.Page.getAttribute(_stateFieldName).setValue(_savedState);
            }
        });

    }
}

$(document).bind('click', function (event) {
    if (_cityDdl && _cityDdl.DynamicDropDown.IsOpen() && _cityDdl.DynamicDropDown.TargetIsThis(event.target.id)) {
        Xrm.Page.getAttribute(_cityFieldName).setValue(_savedCity);
        Xrm.Page.getAttribute(_stateFieldName).setValue(_savedState);
        _cityDdl.DynamicDropDown.Close(300);
    }
});

;(function ($) {
    var DynamicDropDown = function () {
        var _ddKey = "dyndd_";
        var _background;
        var _obj;
        var _spanDiv;
        var _defaultMap;
        var _defaultHoverMap;
        var _items;
        var _selectedIndex;
        var _selectedValue;
        var _selectedText;
        var _isDropdownOpen;
        
        /*********************** Events ***********************/
        
        var onitemselected = null;

        /*********************** Constructor ***********************/

        this.Create = function () {
            _obj = $('<div id="' + _ddKey + 'Body"></div>');
            _obj.css({
                'display' : 'none',
                'position' : 'absolute',
                'top' : '0px',
                'left' : '0px',
                'z-index' : '1001'
            });
            
            _background = $('<div id="' + _ddKey + 'bg"></div>');
            _background.css({
                'display' : 'none',
                'background-color' : '#000',
                'opacity': '0.8',
                'filter' : 'alpha(opacity=80)',
                'position' : 'absolute',
                'top' : '0px',
                'left' : '0px',
                'min-width' : '100%',
                'min-height' : '100%',
                'width' : '100%',
                'height' : '100%',
                'z-index' : '1000'
            });

            $(document.body).append(_obj);
            $(document.body).append(_background);

            _obj.bind('click', function (event) {
                if (event.target.id.indexOf(_ddKey + "Item") > -1) {
                    _selectedIndex = parseInt(event.target.id.replace(_ddKey + "Item", ""));
                    if (!isNaN(_selectedIndex)) {
                        _selectedValue = _items[_selectedIndex].value;
                        _selectedText = _items[_selectedIndex].text;
                        onitemselected();
                    }
                }
            });

            _items = [];
            return _obj;
        };
        
        /*********************** Public Methods ***********************/

        this.SetDefaultCss = function (cssMap) {
            _obj.css(cssMap);
        };

        this.SetDefaultItemCss = function (cssMap) {
            _defaultMap = cssMap;
        };

        this.SetDefaultItemHoverCss = function (cssMap) {
            _defaultHoverMap = cssMap;
        };

        this.CreateHeader = function (text, cssMap) {
            _spanDiv = $('<div id="' + _ddKey + 'Header"><span>' + text + '</span></div>');
            appendDiv(_spanDiv, cssMap);
        };

        this.AddItem = function (value, text, cssMap) {
            var itemCount = _items.length;
            _items[itemCount] = { value : value, text : text };

            var innerDiv = $('<div id="' + _ddKey + 'Item' + itemCount + '">' + text + '</div>');
            innerDiv.mouseover(function () {
                $(this).css(_defaultHoverMap);
            });
            appendDiv(innerDiv, cssMap);
        };

        this.Open = function (speed) {
            var parent = window;
            _obj.css({
                "top": ((($(parent).height() - _obj.outerHeight()) / 2) + $(parent).scrollTop() + "px"),
                "left": ((($(parent).width() - _obj.outerWidth()) / 2) + $(parent).scrollLeft() + "px")
            });

            _background.fadeIn(speed);
            _obj.fadeIn(speed);
            _isDropdownOpen = true;
        };

        this.Close = function (speed) {
            _obj.fadeOut(speed);
            _background.fadeOut(speed);
            _isDropdownOpen = false;
        };

        this.IsOpen = function () {
            return _isDropdownOpen;
        };

        this.SelectedIndex = function () {
            return _selectedIndex;
        };

        this.SelectedValue = function () {
            return _selectedValue;
        };

        this.SelectedText = function () {
            return _selectedText;
        };

        this.Clear = function () {
            _obj.children().each(function (key, value) {
                if (value.id.indexOf(_ddKey + "Item") > -1) {
                    $(value).remove();
                }
            });
        };

        this.ClearSelected = function () {
            _selectedIndex = -1;
            _selectedValue = "";
            _selectedText = "";
        };

        this.TargetIsThis = function (targetId) {
            return (targetId.indexOf(_ddKey) > -1);
        };

        this.bind = function (event, handler) {
            if (event.toLowerCase() == "itemselected") {
                onitemselected = handler;
            }
        };
        
        /*********************** Private Methods ***********************/

        var appendDiv = function (div, cssMap) {
            var newMap = [];
            for (key in _defaultMap) {
                newMap[key] = _defaultMap[key];
            }
            for (key in cssMap) {
                newMap[key] = cssMap[key];
            }
            div.css(newMap);
            div.mouseout(function () {
                $(this).css(newMap);
            });
            _obj.append(div);
        };
                
    };

    $.fn.MakeDynamicDropDown = function () {
        // Return early if this element already has a plugin instance
        if (this.DynamicDropDown) return;

        // Store plugin object as a property on the element
        this.DynamicDropDown = new DynamicDropDown();
        this.DynamicDropDown.Create();
    };

})(jQuery);

Revision: 58160
at June 29, 2012 04:32 by evshell18


Updated Code
///<reference path="XrmPage-vsdoc.js"/>
///<reference path="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1-vsdoc.js"/>

/*
- This code originally written in June 2011 by Bill Caldwell (dynamicscrmdenver.com) from McGladrey
- This code was modified in October 2011 by Bill C to consume the latest yahoo geocode services
- This code was modified on 5/25/2012 by Bill C to provide international postal code functionality
- This code was modified on 6/27/2012 by Evan Kaiser to make the country field parameter optional, 
to allow the choice of using full or abbreviated state name, as well as to provide support for multiple 
browsers using the JQuery library.
- NOTE: Code requires that the page using it first includes a reference to JQuery and JSON. Here is a link to a
managed CRM solution containing JQuery and JSON2 Web Resources that you can include on your CRM forms:
https://skydrive.live.com/embedicon.aspx/.Public/jQueryCRM2011_1_6_0_0_managed.zip?cid=0f98a78f1c3c4457&sc=documents

o Parameters:
-- abbreviateState defaults to false, so unless it is specifically passed in as "true", it will use the full state name
-- The user is not required to enter the country (will default to US)
-- usage: pccd_ZipCodeLookup("address1_postalcode", "address1_city", "address1_stateorprovince", true/false, "address1_country");
*/
var cityTypeName = "Town";
var stateTypeName = "State";
function pccd_ZipCodeLookup(zipFieldName, cityFieldName, stateFieldName, abbreviateState, countryFieldName) {

    Xrm.Page.getAttribute(cityFieldName).setValue("Localizing...");
    Xrm.Page.getAttribute(stateFieldName).setValue(null);

    if (arguments.length < 4) {
        abbreviateState = false;
    }

    // Verify that the field is valid
    var zip = Xrm.Page.getAttribute(zipFieldName).getValue();
    if (zip != null) {

        // define Yahoo YQL query
        var wsql = 'select * from geo.places where text="' + zip + '"';

        // pass country 
        var country = null;
        if (arguments.length > 4 && countryFieldName.length > 0) {
            country = Xrm.Page.getAttribute(countryFieldName).getValue();
        }
        if (country == null) {
            country = "United States";
        }
        wsql = wsql + ' and country="' + country + '"';

        // get url to Yahoo YQL service 
        yqlUrl = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent(wsql) + '&format=json&callback=?';

        $.getJSON(yqlUrl, function (r) {

            var city, state, stateCode;
            if (r.query.count == 1) {

                var node;
                for (key in r.query.results.place) {

                    node = r.query.results.place[key];
                    if (node && node.type && node.type == cityTypeName) {
                        city = node.content;
                    }
                    else if (node && node.type && node.type == stateTypeName) {
                        state = node.content;
                        stateCode = node.code.slice(-2);
                    }

                }

                Xrm.Page.getAttribute(cityFieldName).setValue(city);

                var stateAttribute = Xrm.Page.getAttribute(stateFieldName);
                var stateText = state;
                if (abbreviateState) {
                    stateText = stateCode;
                }
                if (stateAttribute.getAttributeType() == "optionset") {
                    var options = stateAttribute.getOptions();
                    for (var i = 0; i < options.length; i++) {
                        if (options[i].text == stateText) {
                            stateAttribute.setValue(options[i].value);
                        }
                    }
                }
                else {
                    stateAttribute.setValue(stateText);
                }
            }
            else {
                alert("ZipCode cannot be found");
                // If zip code is not found set fields to null (state was already cleared at the beginning).
                Xrm.Page.getAttribute(cityFieldName).setValue(null);
            }
        });
    }
    else {
        // If zip code is not entered, set fields to null (state was already cleared at the beginning).
        Xrm.Page.getAttribute(cityFieldName).setValue(null);
    }
}

Revision: 58159
at June 29, 2012 04:22 by evshell18


Updated Code
///<reference path="XrmPage-vsdoc.js"/>
///<reference path="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1-vsdoc.js"/>

/*
- This code originally written in June 2011 by Bill Caldwell (dynamicscrmdenver.com) from McGladrey
- This code was modified in October 2011 by Bill C to consume the latest yahoo geocode services
- This code was modified on 5/25/2012 by Bill C to provide international postal code functionality
- This code was modified on 6/27/2012 by Evan Kaiser to make the country field parameter optional, 
to allow the choice of using full or abbreviated state name, as well as to provide support for multiple 
browsers using the JQuery library.
- NOTE: Code requires that the page using it first includes a reference to JQuery and JSON.

o Parameters:
-- abbreviateState defaults to false, so unless it is specifically passed in as "true", it will use the full state name
-- The user is not required to enter the country (will default to US)
-- usage: ZipCodeLookup("address1_postalcode", "address1_city", "address1_stateorprovince", true/false, "address1_country");
*/
var cityTypeName = "Town";
var stateTypeName = "State";
function ZipCodeLookup(zipFieldName, cityFieldName, stateFieldName, abbreviateState, countryFieldName) {

    Xrm.Page.getAttribute(cityFieldName).setValue("Localizing...");
    Xrm.Page.getAttribute(stateFieldName).setValue(null);

    if (arguments.length < 4) {
        abbreviateState = false;
    }

    // Verify that the field is valid
    var zip = Xrm.Page.getAttribute(zipFieldName).getValue();
    if (zip != null) {

        // define Yahoo YQL query
        var wsql = 'select * from geo.places where text="' + zip + '"';

        // pass country 
        var country = null;
        if (arguments.length > 4 && countryFieldName.length > 0) {
            country = Xrm.Page.getAttribute(countryFieldName).getValue();
        }
        if (country == null) {
            country = "United States";
        }
        wsql = wsql + ' and country="' + country + '"';

        // get url to Yahoo YQL service 
        yqlUrl = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent(wsql) + '&format=json&callback=?';

        $.getJSON(yqlUrl, function (r) {

            var city, state, stateCode;
            if (r.query.count == 1) {

                var node;
                for (key in r.query.results.place) {

                    node = r.query.results.place[key];
                    if (node && node.type && node.type == cityTypeName) {
                        city = node.content;
                    }
                    else if (node && node.type && node.type == stateTypeName) {
                        state = node.content;
                        stateCode = node.code.slice(-2);
                    }

                }

                Xrm.Page.getAttribute(cityFieldName).setValue(city);

                var stateAttribute = Xrm.Page.getAttribute(stateFieldName);
                var stateText = state;
                if (abbreviateState) {
                    stateText = stateCode;
                }
                if (stateAttribute.getAttributeType() == "optionset") {
                    var options = stateAttribute.getOptions();
                    for (var i = 0; i < options.length; i++) {
                        if (options.text == stateText) {
                            stateAttribute.setValue(options.value);
                        }
                    }
                }
                else {
                    stateAttribute.setValue(stateText);
                }
            }
            else {
                alert("ZipCode cannot be found");
                // If zip code is not found set fields to null (state was already cleared at the beginning).
                Xrm.Page.getAttribute(cityFieldName).setValue(null);
            }
        });
    }
    else {
        // If zip code is not entered, set fields to null (state was already cleared at the beginning).
        Xrm.Page.getAttribute(cityFieldName).setValue(null);
    }
}

Revision: 58158
at June 29, 2012 04:13 by evshell18


Updated Code
///<reference path="XrmPage-vsdoc.js"/>
///<reference path="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1-vsdoc.js"/>

/*
- This code originally written in June 2011 by Bill Caldwell (dynamicscrmdenver.com) from McGladrey
- This code was modified in October 2011 by Bill C to consume the latest yahoo geocode services
- This code was modified on 5/25/2012 by Bill C to provide international postal code functionality
- This code was modified on 6/27/2012 by Evan Kaiser to make the country field parameter optional, 
to allow the choice of using full or abbreviated state name, as well as to provide support for multiple 
browsers using the JQuery library.
- NOTE: Code requires that the page using it first includes a reference to JQuery and JSON.

o Parameters:
-- abbreviateState defaults to false, so unless it is specifically passed in as "true", it will use the full state name
-- The user is not required to enter the country (will default to US)
-- usage: pccd_ZipCodeLookup("address1_postalcode", "address1_city", "address1_stateorprovince", true/false, "address1_country");
*/
var cityTypeName = "Town";
var stateTypeName = "State";
function pccd_ZipCodeLookup(zipFieldName, cityFieldName, stateFieldName, abbreviateState, countryFieldName) {

    if (arguments.length < 4) {
        abbreviateState = false;
    }

    // Verify that the field is valid
    var zip = Xrm.Page.getAttribute(zipFieldName).getValue();
    if (zip != null) {

        // define Yahoo YQL query
        var wsql = 'select * from geo.places where text="' + zip + '"';

        // pass country 
        var country = null;
        if (arguments.length > 4 && countryFieldName.length > 0) {
            country = Xrm.Page.getAttribute(countryFieldName).getValue();
        }
        if (country == null) {
            country = "United States";
        }
        wsql = wsql + ' and country="' + country + '"';

        // get url to Yahoo YQL service 
        yqlUrl = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent(wsql) + '&format=json&callback=?';

        $.getJSON(yqlUrl, function (r) {

            var city, state, stateCode;
            if (r.query.count == 1) {

                var node;
                for (key in r.query.results.place) {

                    node = r.query.results.place[key];
                    if (node && node.type && node.type == cityTypeName) {
                        city = node.content;
                    }
                    else if (node && node.type && node.type == stateTypeName) {
                        state = node.content;
                        stateCode = node.code.slice(-2);
                    }

                }

                Xrm.Page.getAttribute(cityFieldName).setValue(city);

                var stateAttribute = Xrm.Page.getAttribute(stateFieldName);
                var stateText = state;
                if (abbreviateState) {
                    stateText = stateCode;
                }
                if (stateAttribute.getAttributeType() == "optionset") {
                    var options = stateAttribute.getOptions();
                    for (var i = 0; i < options.length; i++) {
                        if (options.text == stateText) {
                            stateAttribute.setValue(options.value);
                        }
                    }
                }
                else {
                    stateAttribute.setValue(stateText);
                }
            }
            else {
                alert("ZipCode cannot be found");
                // if zip code is not found set fields to null
                Xrm.Page.getAttribute(cityFieldName).setValue(null)
                Xrm.Page.getAttribute(stateFieldName).setValue(null)
            }
        });
    }
    else {
        // if zip code is not entered, set fields to null
        Xrm.Page.getAttribute(cityFieldName).setValue(null)
        Xrm.Page.getAttribute(stateFieldName).setValue(null)
    }
}

Revision: 58157
at June 28, 2012 07:29 by evshell18


Updated Code
///<reference path="XrmPage-vsdoc.js"/>
///<reference path="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1-vsdoc.js"/>

/*
- This code originally written in June 2011 by Bill Caldwell (dynamicscrmdenver.com) from McGladrey
- This code was modified in October 2011 by Bill C to consume the latest yahoo geocode services
- This code was modified on 5/25/2012 by Bill C to provide international postal code functionality
- This code was modified on 6/27/2012 by Evan Kaiser to allow the choice of using full or abbreviated state 
name as well as to provide support for multiple browsers using the JQuery library 
- NOTE: (JQuery must be included on the page that uses this)

o Parameters:
-- abbreviateState defaults to false, so unless it is specifically passed in as "true", it will use the full state name
-- The user is not required to enter the country (will default to US)
-- usage: ZipCodeLookup("address1_postalcode", "address1_city", "address1_stateorprovince", true/false, "address1_country");
*/
function ZipCodeLookup(zipFieldName, cityFieldName, stateFieldName, abbreviateState, countryFieldName) {

    // Verify that the field is valid
    var zip = Xrm.Page.getAttribute(zipFieldName).getValue();
    if (zip != null) {
        
        // get url to Yahoo geocode service 
        var url = "http://where.yahooapis.com/geocode?appid=MicrosoftCRM";

        //determine which state text to use
        var stateKey = "state";
        if (arguments.length > 3 && abbreviateState) {
            stateKey = "statecode";
        }
        
        //pass country 
        var country = null;
        if (arguments.length > 4 && countryFieldName.length > 0) {
            country = Xrm.Page.getAttribute(countryFieldName).getValue();
        }
        if (country == null) {
            country = "United States";
        }

        url += "&country=" + country + "&postal=" + zip;

        $.ajax({
            url: url,
            cache: false
        }).done(function (httpResponse) {

            // populate city, state and country in CRM if zip is valid
            if (httpResponse.selectSingleNode("ResultSet/Result/city") == null) {

                alert("ZipCode cannot be found");

                // if zip code is not found set fields to null
                Xrm.Page.getAttribute(cityFieldName).setValue(null)
                Xrm.Page.getAttribute(stateFieldName).setValue(null)
                return;
            }
            else {
                Xrm.Page.getAttribute(cityFieldName).setValue(httpResponse.selectSingleNode("ResultSet/Result/city").text);

                var stateAttribute = Xrm.Page.getAttribute(stateFieldName);
                var stateText = httpResponse.selectSingleNode("ResultSet/Result/" + stateKey).text;
                if (stateAttribute.getAttributeType() == "optionset") {
                    var options = stateAttribute.getOptions();
                    for (var i = 0; i < options.length; i++) {
                        if (options.text == stateText) {
                            stateAttribute.setValue(options.value);
                        }
                    }
                }
                else {
                    stateAttribute.setValue(stateText);
                }
            }
        });
    }
    else {
        // if zip code is not entered, set fields to null
        Xrm.Page.getAttribute(cityFieldName).setValue(null)
        Xrm.Page.getAttribute(stateFieldName).setValue(null)
    }
}

Revision: 58156
at June 28, 2012 07:26 by evshell18


Updated Code
///<reference path="XrmPage-vsdoc.js"/>
///<reference path="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1-vsdoc.js"/>

function ZipCodeLookup(zipFieldName, cityFieldName, stateFieldName, abbreviateState, countryFieldName) {
    /*
    - This code originally written in June 2011 by Bill Caldwell (dynamicscrmdenver.com) from McGladrey
    - This code was modified in October 2011 by Bill C to consume the latest yahoo geocode services
    - This code was modified on 5/25/2012 by Bill C to provide international postal code functionality
    - This code was modified on 6/27/2012 by Evan Kaiser to allow the choice of using full or abbreviated state 
      name as well as to provide support for multiple browsers using the JQuery library 
    - NOTE: (JQuery must be included on the page that uses this)

    o Parameters:
      -- abbreviateState defaults to false, so unless it is specifically passed in as "true", it will use the full state name
      -- The user is not required to enter the country (will default to US)
      -- usage: ZipCodeLookup("address1_postalcode", "address1_city", "address1_stateorprovince", true/false, "address1_country");
    */
    // Verify that the field is valid
    var zip = Xrm.Page.getAttribute(zipFieldName).getValue();
    if (zip != null) {
        
        // get url to Yahoo geocode service 
        var url = "http://where.yahooapis.com/geocode?appid=MicrosoftCRM";

        //determine which state text to use
        var stateKey = "state";
        if (arguments.length > 3 && abbreviateState) {
            stateKey = "statecode";
        }
        
        //pass country 
        var country = null;
        if (arguments.length > 4 && countryFieldName.length > 0) {
            country = Xrm.Page.getAttribute(countryFieldName).getValue();
        }
        if (country == null) {
            country = "United States";
        }

        url += "&country=" + country + "&postal=" + zip;

        $.ajax({
            url: url,
            cache: false
        }).done(function (httpResponse) {

            // populate city, state and country in CRM if zip is valid
            if (httpResponse.selectSingleNode("ResultSet/Result/city") == null) {

                alert("ZipCode cannot be found");

                // if zip code is not found set fields to null
                Xrm.Page.getAttribute(cityFieldName).setValue(null)
                Xrm.Page.getAttribute(stateFieldName).setValue(null)
                return;
            }
            else {
                Xrm.Page.getAttribute(cityFieldName).setValue(httpResponse.selectSingleNode("ResultSet/Result/city").text);

                var stateAttribute = Xrm.Page.getAttribute(stateFieldName);
                var stateText = httpResponse.selectSingleNode("ResultSet/Result/" + stateKey).text;
                if (stateAttribute.getAttributeType() == "optionset") {
                    var options = stateAttribute.getOptions();
                    for (var i = 0; i < options.length; i++) {
                        if (options.text == stateText) {
                            stateAttribute.setValue(options.value);
                        }
                    }
                }
                else {
                    stateAttribute.setValue(stateText);
                }
            }
        });
    }
    else {
        // if zip code is not entered, set fields to null
        Xrm.Page.getAttribute(cityFieldName).setValue(null)
        Xrm.Page.getAttribute(stateFieldName).setValue(null)
    }
}

Revision: 58155
at June 28, 2012 07:26 by evshell18


Updated Code
///<reference path="XrmPage-vsdoc.js"/>
///<reference path="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1-vsdoc.js"/>

function ZipCodeLookup(zipFieldName, cityFieldName, stateFieldName, abbreviateState, countryFieldName) {
    /*
    - This code originally written in June 2011 by Bill Caldwell (dynamicscrmdenver.com) from McGladrey
    - This code was modified in October 2011 by Bill C to consume the latest yahoo geocode services
    - This code was modified on 5/25/2012 by Bill C to provide international postal code functionality
    - This code was modified on 6/27/2012 by Evan Kaiser to allow the choice of using full or abbreviated state 
      name as well as to provide support for multiple browsers using the JQuery library 
    - NOTE: (JQuery must be included on the page that uses this)

    o Parameters:
      -- abbreviateState defaults to false, so unless it is specifically passed in as "true", it will use the full state name
      -- The user is not required to enter the country (will default to US)
      -- usage: ZipCodeLookup("address1_postalcode", "address1_city", "address1_stateorprovince", "address1_country", true/false);
    */
    // Verify that the field is valid
    var zip = Xrm.Page.getAttribute(zipFieldName).getValue();
    if (zip != null) {
        
        // get url to Yahoo geocode service 
        var url = "http://where.yahooapis.com/geocode?appid=MicrosoftCRM";

        //determine which state text to use
        var stateKey = "state";
        if (arguments.length > 3 && abbreviateState) {
            stateKey = "statecode";
        }
        
        //pass country 
        var country = null;
        if (arguments.length > 4 && countryFieldName.length > 0) {
            country = Xrm.Page.getAttribute(countryFieldName).getValue();
        }
        if (country == null) {
            country = "United States";
        }

        url += "&country=" + country + "&postal=" + zip;

        $.ajax({
            url: url,
            cache: false
        }).done(function (httpResponse) {

            // populate city, state and country in CRM if zip is valid
            if (httpResponse.selectSingleNode("ResultSet/Result/city") == null) {

                alert("ZipCode cannot be found");

                // if zip code is not found set fields to null
                Xrm.Page.getAttribute(cityFieldName).setValue(null)
                Xrm.Page.getAttribute(stateFieldName).setValue(null)
                return;
            }
            else {
                Xrm.Page.getAttribute(cityFieldName).setValue(httpResponse.selectSingleNode("ResultSet/Result/city").text);

                var stateAttribute = Xrm.Page.getAttribute(stateFieldName);
                var stateText = httpResponse.selectSingleNode("ResultSet/Result/" + stateKey).text;
                if (stateAttribute.getAttributeType() == "optionset") {
                    var options = stateAttribute.getOptions();
                    for (var i = 0; i < options.length; i++) {
                        if (options.text == stateText) {
                            stateAttribute.setValue(options.value);
                        }
                    }
                }
                else {
                    stateAttribute.setValue(stateText);
                }
            }
        });
    }
    else {
        // if zip code is not entered, set fields to null
        Xrm.Page.getAttribute(cityFieldName).setValue(null)
        Xrm.Page.getAttribute(stateFieldName).setValue(null)
    }
}

Revision: 58154
at June 28, 2012 07:24 by evshell18


Updated Code
///<reference path="XrmPage-vsdoc.js"/>
///<reference path="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1-vsdoc.js"/>

function ZipCodeLookup(zipFieldName, cityFieldName, stateFieldName, abbreviateState, countryFieldName) {
    /*
    - This code originally written in June 2011 by Bill Caldwell (dynamicscrmdenver.com) from McGladrey
    - This code was modified in October 2011 by Bill C to consume the latest yahoo geocode services
    - This code was modified on 5/25/2012 by Bill C to provide international postal code functionality
    - This code was modified on 6/27/2012 by Evan Kaiser to allow the choice of using full or abbreviated state name as well as to provide support for multiple browsers using the JQuery library 
    - NOTE: (JQuery must be included on the page that uses this)

    o Parameters:
      -- abbreviateState defaults to false, so unless it is specifically passed in as "true", it will use the full state name
      -- The user is not required to enter the country (will default to US)
      -- usage: ZipCodeLookup("address1_postalcode", "address1_city", "address1_stateorprovince", "address1_country", true/false);
    */
    // Verify that the field is valid
    var zip = Xrm.Page.getAttribute(zipFieldName).getValue();
    if (zip != null) {
        
        // get url to Yahoo geocode service 
        var url = "http://where.yahooapis.com/geocode?appid=MicrosoftCRM";

        //determine which state text to use
        var stateKey = "state";
        if (arguments.length > 3 && abbreviateState) {
            stateKey = "statecode";
        }
        
        //pass country 
        var country = null;
        if (arguments.length > 4 && countryFieldName.length > 0) {
            country = Xrm.Page.getAttribute(countryFieldName).getValue();
        }
        if (country == null) {
            country = "United States";
        }

        url += "&country=" + country + "&postal=" + zip;

        $.ajax({
            url: url,
            cache: false
        }).done(function (httpResponse) {

            // populate city, state and country in CRM if zip is valid
            if (httpResponse.selectSingleNode("ResultSet/Result/city") == null) {

                alert("ZipCode cannot be found");

                // if zip code is not found set fields to null
                Xrm.Page.getAttribute(cityFieldName).setValue(null)
                Xrm.Page.getAttribute(stateFieldName).setValue(null)
                return;
            }
            else {
                Xrm.Page.getAttribute(cityFieldName).setValue(httpResponse.selectSingleNode("ResultSet/Result/city").text);

                var stateAttribute = Xrm.Page.getAttribute(stateFieldName);
                var stateText = httpResponse.selectSingleNode("ResultSet/Result/" + stateKey).text;
                if (stateAttribute.getAttributeType() == "optionset") {
                    var options = stateAttribute.getOptions();
                    for (var i = 0; i < options.length; i++) {
                        if (options.text == stateText) {
                            stateAttribute.setValue(options.value);
                        }
                    }
                }
                else {
                    stateAttribute.setValue(stateText);
                }
            }
        });
    }
    else {
        // if zip code is not entered, set fields to null
        Xrm.Page.getAttribute(cityFieldName).setValue(null)
        Xrm.Page.getAttribute(stateFieldName).setValue(null)
    }
}

Revision: 58153
at June 28, 2012 07:22 by evshell18


Updated Code
///<reference path="XrmPage-vsdoc.js"/>
///<reference path="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1-vsdoc.js"/>

function ZipCodeLookup(zipFieldName, cityFieldName, stateFieldName, countryFieldName, abbreviateState) {
    /*
    - This code originally written in June 2011 by Bill Caldwell (dynamicscrmdenver.com) from McGladrey
    - This code was modified in October 2011 by Bill C to consume the latest yahoo geocode services
    - This code was modified on 5/25/2012 by Bill C to provide international postal code functionality
    - This code was modified on 6/27/2012 by Evan Kaiser to allow the choice of using full or abbreviated state name as well as to provide support for multiple browsers using the JQuery library 
    - NOTE: (JQuery must be included on the page that uses this)

    o Parameters:
      -- The user is not required to enter the country (will default to US)
      -- abbreviateState defaults to false, so unless it is specifically passed in, it will use the full state name
      -- usage: ZipCodeLookup("address1_postalcode", "address1_city", "address1_stateorprovince", "address1_country", true/false);
    */
    // Verify that the field is valid
    var zip = Xrm.Page.getAttribute(zipFieldName).getValue();
    if (zip != null) {
        
        // get url to Yahoo geocode service 
        var url = "http://where.yahooapis.com/geocode?appid=MicrosoftCRM";
        
        //pass country 
        var country = null;
        if (arguments.length > 3 && countryFieldName.length > 0) {
            country = Xrm.Page.getAttribute(countryFieldName).getValue();
        }
        if (country == null) {
            country = "United States";
        }
        
        //determine which state text to use
        var stateKey = "state";
        if (arguments.length > 4 && abbreviateState) {
            stateKey = "statecode";
        }
        url += "&country=" + country + "&postal=" + zip;

        $.ajax({
            url: url,
            cache: false
        }).done(function (httpResponse) {

            // populate city, state and country in CRM if zip is valid
            if (httpResponse.selectSingleNode("ResultSet/Result/city") == null) {

                alert("ZipCode cannot be found");

                // if zip code is not found set fields to null
                Xrm.Page.getAttribute(cityFieldName).setValue(null)
                Xrm.Page.getAttribute(stateFieldName).setValue(null)
                return;
            }
            else {
                Xrm.Page.getAttribute(cityFieldName).setValue(httpResponse.selectSingleNode("ResultSet/Result/city").text);

                var stateAttribute = Xrm.Page.getAttribute(stateFieldName);
                var stateText = httpResponse.selectSingleNode("ResultSet/Result/" + stateKey).text;
                if (stateAttribute.getAttributeType() == "optionset") {
                    var options = stateAttribute.getOptions();
                    for (var i = 0; i < options.length; i++) {
                        if (options.text == stateText) {
                            stateAttribute.setValue(options.value);
                        }
                    }
                }
                else {
                    stateAttribute.setValue(stateText);
                }
            }
        });
    }
    else {
        // if zip code is not entered, set fields to null
        Xrm.Page.getAttribute(cityFieldName).setValue(null)
        Xrm.Page.getAttribute(stateFieldName).setValue(null)
    }
}

Revision: 58152
at June 28, 2012 07:19 by evshell18


Updated Code
///<reference path="XrmPage-vsdoc.js"/>
///<reference path="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1-vsdoc.js"/>

function pccd_ZipCodeLookup(zipFieldName, cityFieldName, stateFieldName, countryFieldName, abbreviateState) {
    /*
    - This code originally written in June 2011 by Bill Caldwell (dynamicscrmdenver.com) from McGladrey
    - This code was modified in October 2011 by Bill C to consume the latest yahoo geocode services
    - This code was modified on 5/25/2012 by Bill C to provide international postal code functionality
    - This code was modified on 6/27/2012 by Evan Kaiser to allow the choice of using full or abbreviated state name as well as to provide support for multiple browsers using the JQuery library 
    - NOTE: (JQuery must be included on the page that uses this)

    o Parameters:
      -- The user is not required to enter the country (will default to US)
      -- abbreviateState defaults to false, so unless it is specifically passed in, it will use the full state name
      -- usage: ZipCodeLookup("address1_postalcode", "address1_city", "address1_stateorprovince", "address1_country", true/false);
    */
    // Verify that the field is valid
    var zip = Xrm.Page.getAttribute(zipFieldName).getValue();
    if (zip != null) {
        
        // get url to Yahoo geocode service 
        var url = "http://where.yahooapis.com/geocode?appid=MicrosoftCRM";
        
        //pass country 
        var country = null;
        if (arguments.length > 3 && countryFieldName.length > 0) {
            country = Xrm.Page.getAttribute(countryFieldName).getValue();
        }
        if (country == null) {
            country = "United States";
        }
        
        //determine which state text to use
        var stateKey = "state";
        if (arguments.length > 4 && abbreviateState) {
            stateKey = "statecode";
        }
        url += "&country=" + country + "&postal=" + zip;

        $.ajax({
            url: url,
            cache: false
        }).done(function (httpResponse) {

            // populate city, state and country in CRM if zip is valid
            if (httpResponse.selectSingleNode("ResultSet/Result/city") == null) {

                alert("ZipCode cannot be found");

                // if zip code is not found set fields to null
                Xrm.Page.getAttribute(cityFieldName).setValue(null)
                Xrm.Page.getAttribute(stateFieldName).setValue(null)
                return;
            }
            else {
                Xrm.Page.getAttribute(cityFieldName).setValue(httpResponse.selectSingleNode("ResultSet/Result/city").text);

                var stateAttribute = Xrm.Page.getAttribute(stateFieldName);
                var stateText = httpResponse.selectSingleNode("ResultSet/Result/" + stateKey).text;
                if (stateAttribute.getAttributeType() == "optionset") {
                    var options = stateAttribute.getOptions();
                    for (var i = 0; i < options.length; i++) {
                        if (options.text == stateText) {
                            stateAttribute.setValue(options.value);
                        }
                    }
                }
                else {
                    stateAttribute.setValue(stateText);
                }
            }
        });
    }
    else {
        // if zip code is not entered, set fields to null
        Xrm.Page.getAttribute(cityFieldName).setValue(null)
        Xrm.Page.getAttribute(stateFieldName).setValue(null)
    }
}

Revision: 58151
at June 28, 2012 07:16 by evshell18


Initial Code
///<reference path="XrmPage-vsdoc.js"/>
///<reference path="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1-vsdoc.js"/>

function pccd_ZipCodeLookup(zipFieldName, cityFieldName, stateFieldName, countryFieldName, abbreviateState) {
    /*
    This code originally written in June 2011 by Bill Caldwell (dynamicscrmdenver.com) from McGladrey
    This code was modified in October 2011 by Bill C to consume the latest yahoo geocode services
    This code was modified on 5/25/2012 by Bill C to provide international postal code functionality
    This code was modified on 6/27/2012 by Evan Kaiser to allow the choice of using full or abbreviated state name as well as to provide support for multiple browsers using the JQuery library (JQuery must be included on the page that uses this).

    The code requires certain IE security settings must be changed (under miscellaneous, change "access data sources across domains" to ‘enable’.
    The user is not required to enter the country (will default to US)
    abbreviateState defaults to false, so unless it is specifically passed in, it will use the full state name
    usage: ZipCodeLookup("address1_postalcode", "address1_city", "address1_stateorprovince", "address1_country", true/false);
    */
    // Verify that the field is valid
    var zip = Xrm.Page.getAttribute(zipFieldName).getValue();
    if (zip != null) {
        
        // get url to Yahoo geocode service 
        var url = "http://where.yahooapis.com/geocode?appid=MicrosoftCRM";
        
        //pass country 
        var country = null;
        if (arguments.length > 3 && countryFieldName.length > 0) {
            country = Xrm.Page.getAttribute(countryFieldName).getValue();
        }
        if (country == null) {
            country = "United States";
        }
        
        //determine which state text to use
        var stateKey = "state";
        if (arguments.length > 4 && abbreviateState) {
            stateKey = "statecode";
        }
        url += "&country=" + country + "&postal=" + zip;

        $.ajax({
            url: url,
            cache: false
        }).done(function (httpResponse) {

            // populate city, state and country in CRM if zip is valid
            if (httpResponse.selectSingleNode("ResultSet/Result/city") == null) {

                alert("ZipCode cannot be found");

                // if zip code is not found set fields to null
                Xrm.Page.getAttribute(cityFieldName).setValue(null)
                Xrm.Page.getAttribute(stateFieldName).setValue(null)
                return;
            }
            else {
                Xrm.Page.getAttribute(cityFieldName).setValue(httpResponse.selectSingleNode("ResultSet/Result/city").text);

                var stateAttribute = Xrm.Page.getAttribute(stateFieldName);
                var stateText = httpResponse.selectSingleNode("ResultSet/Result/" + stateKey).text;
                if (stateAttribute.getAttributeType() == "optionset") {
                    var options = stateAttribute.getOptions();
                    for (var i = 0; i < options.length; i++) {
                        if (options.text == stateText) {
                            stateAttribute.setValue(options.value);
                        }
                    }
                }
                else {
                    stateAttribute.setValue(stateText);
                }
            }
        });
    }
    else {
        // if zip code is not entered, set fields to null
        Xrm.Page.getAttribute(cityFieldName).setValue(null)
        Xrm.Page.getAttribute(stateFieldName).setValue(null)
    }
}

Initial URL


Initial Description
Allows the ability to fill City and State fields in CRM 2011 based on the value of a Zip Code field (and optionally Country). 

Requires JQuery and JSON

Uses Yahoo geocode service

Originally written by Bill Caldwell ( http://dynamicscrmdenver.com/2012/05/25/dynamics-crm-2011-javascript-zipcodepostal-code-lookup/ )

Initial Title
CRM 2011 Zip Code Lookup

Initial Tags
jquery, json

Initial Language
JavaScript