Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery UI Autocomplete: Tell It My 'Label' and 'Value'

Is there a way to tell jQuery UI Autocomplete which JSON array indexes to use as the 'label' and 'value' when those aren't the index names used in the JSON array?

The aray containing my lookup values looks like this (as logged by Firebug):

[ Object { id="12", name="Don Davis" }, Object { id="17", name="Stan Smith" } ]

I want to use 'id' as the 'label' and 'name' as the 'value' but can't figure out how to tell the config object.

My array is contained in a local variable -- there's no Ajax call being made.

This response to another question solves the problem by creating a hidden form input, but it seems likely that there's a cleaner way of handling this.

like image 200
cantera Avatar asked Jun 03 '12 02:06

cantera


People also ask

How does autocomplete set value?

MUI Autocomplete Get Selected Value I used the onChange handler to pass the selected option to the state value's setter. If we want to get the Autocomplete's selected value for use with a form submission, we only need to wrap the Autocomplete in a form element and add a Button with type="submit" .

How does autocomplete work in jQuery?

In the process of searching a specific value, the jQuery UI autocomplete selection feature provides the user with some string suggestions for the input area which effectively saves time. The autocomplete select action is triggered when the user selects one of the options from the pre-populated list.

How can create autocomplete search box in jQuery?

Syntax: $("TagId"). autocomplete({ source : itemList // List of Words. })


1 Answers

From reading the Jquery UI docs you can try something like this:

<script>
    $(function() {
var projects = [ { id: "12",value: "Don Davis" }, { id: "17", value:"Stan Smith" } ]

    $( "#project" ).autocomplete({
        minLength: 0,
        source: projects,
        focus: function( event, ui ) {
            $( "#project" ).val( ui.item.value);
            return false;
        },
        select: function( event, ui ) {
            $( "#project" ).val( ui.item.value);
            $( "#project-id" ).val( ui.item.id);

            return false;
        },
        search: function(event, ui) { console.log(event); console.log(ui) }
    })
    .data( "autocomplete" )._renderItem = function( ul, item ) {
        return $( "<li></li>" )
            .data( "item.autocomplete", item )
            .append( "<a>" + item.value+"</a>" )
            .appendTo( ul );
    };
});​
    </script>
like image 101
Jason Kulatunga Avatar answered Oct 20 '22 23:10

Jason Kulatunga