AutoComplete Widget :: JavaScript Function

DataSource

This DataSource instance points to an in-memory JavaScript function that returns results in an array. The function queries against an in-memory object literal of data that holds the 50 US states and their corresponding postal abbreviations.

AutoComplete

Since the DataSource for this example is already loaded into memory, queries should be very fast to return data. Therefore, the AutoComplete instance is configured to have a query delay of zero seconds. The AutoComplete instance is also configured to display two data fields in its container: the state and its corresponding postal abbreviation. By setting the alwaysShowContainer property to true and customizing appropriate CSS styles, the container has been implemented to always be displayed. Custom event handlers have been hooked into containerExpandEvent and containerCollapseEvent to dynamically update the always open container's contents. Finally, the autoHighlight feature has been enabled to reduce the number of user actions it takes to submit a valid selection.

Find a state:

Sample Code

CSS:


    #statesmod {position:relative;padding:1em;}

    #statesautocomplete {position:relative;margin:1em;width:15em;}/* set width of widget here*/

    #statesinput {position:absolute;width:100%;height:1.4em;}

    #statescontainer {position:absolute;top:1.7em;width:100%;}

    #statescontainer .yui-ac-content {position:absolute;width:100%;height:11em;border:1px solid #404040;background:#fff;overflow:hidden;z-index:9050;}

    #statescontainer .yui-ac-shadow {position:absolute;margin:.3em;width:100%;background:#a0a0a0;z-index:9049;}

    #statescontainer ul {padding:5px 0;width:100%;}

    #statescontainer li {padding:0 5px;cursor:default;white-space:nowrap;}

    #statescontainer li.yui-ac-highlight {background:#ff0;}

    

Markup:


    <!-- AutoComplete begins -->

    <div id="statesmod">

        <form>

            <h2>Find a state:</h2>

            <div id="statesautocomplete">

                <input id="statesinput">

                <div id="statescontainer"></div>

            </div>

        </form>

    </div>

    <!-- AutoComplete ends -->

    

JavaScript:


    function getStates(sQuery) {

        aResults = [];

        if(sQuery.length > 0) {

            var charKey = sQuery.substring(0,1).toLowerCase();

            var oResponse = dataset[charKey];



            if(oResponse) {

                for(var i = oResponse.length-1; i >= 0; i--) {

                    var sKey = oResponse[i].STATE;

                    var sKeyIndex = encodeURI(sKey.toLowerCase()).indexOf(sQuery.toLowerCase());



                    // Query found at the beginning of the key string for STARTSWITH

                    // returns an array of arrays where STATE is index=0, ABBR is index=1

                    if(sKeyIndex === 0) {

                        aResults.unshift([sKey, oResponse[i].ABBR]);

                    }

                }

            }

            return aResults;

        }

        else { return null; }

    }

    

    var dataset =

        {'a': [{"STATE" : "Alabama", "ABBR" : "AL"},

    		{"STATE" : "Alaska", "ABBR" : "AK"},

    		{"STATE" : "Arizona", "ABBR" : "AZ"},

    		{"STATE" : "Arkansas", "ABBR" : "AR"}],

    	'b' : [

    		],

    	'c' : [

    		{"STATE" : "California", "ABBR" : "CA"},

    		{"STATE" : "Colorado", "ABBR" : "CO"},

            {"STATE" : "Connecticut", "ABBR" : "CT"}] // Entire dataset not shown

        };



    // Instantiate data source

    oACDS = new YAHOO.widget.DS_JSFunction(getStates);



    // Instantiate auto complete

    oAutoComp = new YAHOO.widget.AutoComplete('statesinput','statescontainer', oACDS);

    oAutoComp.alwaysShowContainer = true;

    oAutoComp.queryDelay = 0;

    oAutoComp.maxResultsDisplayed = 8;

    oAutoComp.useShadow = true;

    oAutoComp.setBody("
Start typing to find a state
"); oAutoComp.formatResult = function(oResultItem, sQuery) { var sMarkup = oResultItem[0] + " (" + oResultItem[1] + ")"; return (sMarkup); }; // Subscribe to custom events oAutoComp.dataReturnEvent.subscribe(myOnDataReturn); oAutoComp.containerCollapseEvent.subscribe(myOnContainerCollapse);