7

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.

1
  • Yu can do whatever you want if you use a function as the "source" parameter. Commented Jun 3, 2012 at 3:01

3 Answers 3

9

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>
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks - the docs demo also uses the hidden field for 'id' (as in your #project-id field), so I guess that's the officially supported way to do it, other than adjusting the JSON array indexes directly. This way would likely perform better. Thanks again.
Note that that in jquery-ui 1.11 (and possibly earlier), data("autocomplete") should be data("uiAutocomplete")
0

Simply convert your result to an array that contains a list of label-value object

var list= result.map(function (item) { return { label: item.title, value: item.value }; });
$( "#project" ).autocomplete({
    source: list
});

Comments

-2

You must return an array like this: (side server PHP)

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.