Monday, February 13, 2012

jquery ui autocomplete json setup key, "value"

 jquery autocomplete is easy to use and setup. The only thing I had spent time to figure out how it works is the configuration of the json. You must label the 'value' in the json, since I had used 'key' at the first time and it didn't work.

json example:
[{value:'ABC', label:'ABC company'},{value:'BBC',label:'BBC company'},...]

The 'value' is the item back to your input box when you selected from the list, and the 'label' is the item you see in the list.

The following is the example I implemented in the script:
$("#input1").autocomplete({
                    minLength: 0,
                    source: cList, //a json return from ajax
                    select: function( event, ui ) {
                        $(this).val( ui.item.value ); 
                        return false;
                    }               
                }).data("autocomplete")._renderItem = function( ul, item ) {
                        return $( "<li></li>" )
                            .data( "item.autocomplete", item )
                            .append( "<a>" + item.label + "</a>" )
                            .appendTo( ul );
                }

No comments: