JQuery UI Autocomplete: Tell me "Label" and "Value",

Is there a way to tell jQuery UI autocomplete which JSON indexes to use as a “label” and “value” if they are not the index names used in the JSON array?

The arif containing my search values ​​looks like this (as Firebug is registered):

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

I want to use "id" as a "label" and "name" as a "value", but I cannot figure out how to say the configuration object.

My array is contained in a local variable - there is no Ajax call there.

This answer to another question solves the problem by creating a hidden form input, but it seems likely that there is a cleaner way to handle this.

+5
source share
2 answers

From reading JQuery UI, 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>
+7
source

You should return such an array: (side server PHP)

for( ... ){
$suggest = array('value'=>$value,'label'=>$label); }

-1
source

All Articles