jQuery UI Autocomplete: Tell It My 'Label' and 'Value'
Asked Answered
A

3

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.

Astyanax answered 3/6, 2012 at 2:47 Comment(1)
Yu can do whatever you want if you use a function as the "source" parameter.Allochthonous
G
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>
Grassofparnassus answered 3/6, 2012 at 3:32 Comment(2)
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.Astyanax
Note that that in jquery-ui 1.11 (and possibly earlier), data("autocomplete") should be data("uiAutocomplete")Craigie
E
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
});
Ethmoid answered 8/12, 2020 at 16:11 Comment(0)
M
-2

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

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

Mallon answered 6/12, 2016 at 19:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.