How to get JQuery UI Autocomplete work with item id

18,111

Solution 1

From the fine manual:

The local data can be a simple Array of Strings, or it contains Objects for each item in the array, with either a label or value property or both. The label property is displayed in the suggestion menu. The value will be inserted into the input element after the user selected something from the menu.

So the label goes in the drop down menu and the value goes into the <input type="text"> and you want something a little different, you want one thing in the <input type="text"> and menu and another thing in a separate <input type="hidden">.

Suppose you got some raw data like this back from your server:

var raw = [
    { value: 1, label: 'one'   },
    { value: 2, label: 'two'   },
    { value: 3, label: 'three' },
    { value: 4, label: 'four'  }
];

Then you could build an array and a simple mapping object:

var source  = [ ];
var mapping = { };
for(var i = 0; i < raw.length; ++i) {
    source.push(raw[i].label);
    mapping[raw[i].label] = raw[i].value;
}

The source array would be given to .autocomplete() and your select handler would use mapping to figure out what to put in the <input type="hidden">:

$('.tags').autocomplete({
    source: source,
    select: function(event, ui) {
        $('.tags_id').val(mapping[ui.item.value]);
    }
});

Demo: http://jsfiddle.net/ambiguous/GVPPy/

Solution 2

You don't need a mapping. You can set custom attributes to the objects in the source array. The attributes "label" and "value" are reserved. Then the custom attributes such as "id" can be accessed through ui.item.id in the event handler.

$("#input_id").autocomplete({
  source:function(request, response){
    $.ajax({
        url: "/api/autocomplete",
        type: "POST",
        dataType: "json",
        data: { term: request.term },
        success: function(responseData){
            var array = responseData.map(function(element) {
                return {value: element['name'], id: element['id']};
            });
            response(array);
        }
    })
  select: function(event, ui) {
      var name = ui.item.value;
      var id = ui.item.id;
      ...
Share:
18,111
Saher Ahwal
Author by

Saher Ahwal

Software Engineer at Microsoft LinkedIn Profile MEng Thesis: Optimizations to a massively parallel database and support of a shared scan architecture

Updated on June 04, 2022

Comments

  • Saher Ahwal
    Saher Ahwal almost 2 years

    I have seen this post here: jQuery UI autocomplete with item and id but I was not able to figure things out.

    here is my input html:

    <input type="text" class="tags" style="width:250px; height:24px;"> </input>' 
    <input type="hidden" name="tags_id" id="tags_id" />
    

    here is my ajax call:

    var data = {};
    $.get('/tags',data, function(tag_list) {
                    autocomplete_source_list = [];
    
                    for(var i = 0; i < tag_list.length; i++){
                        autocomplete_source_list.push([tag_list[i].fields.display_name, [2,3,4,5,6,7,8,9,1,2]]);
                    }
                    jQuery( ".tags" ).autocomplete({
                        source: autocomplete_source_list,
                        select: function (event, ui) {
                            $(".tags").val(ui.item.label); // display the selected text
                            $(".tags_id").val(ui.item.value); // save selected id to hidden input
                            console.log("selected id: ", ui.item.label)
                        }
                    });
    
                });
    

    How do I set up the ids should I pass a 2d array to source? when I give the source to be just the text then both ui.item.value = ui.item.label = "whatever text". I don't see how id's can be attached.

    Can I get some help please. Thanks