开发者

Getting the Index of the selected item in jquery auto complete

I am using jQuery autocomplete, as follows:

From my PHP file, I am get json encoded arrays - one for ids and one for names.

I fill the autocomplete with names. In the select function, I am able to correctly alert the selected item, but I am not able to get the index of the selected item. How do I get it?

$(function() {
    $.ajax({
        type: "POST",
        url: "get_data.php",
        success: function(data) {
            data_array = jQuery.parseJSON(data);
            $("#my_autocomplete").autocomplete({
                source: data_array.names,
 开发者_如何学Python               select: function(event, ui) {
                    alert(ui.item);
                }
            });

        }
    });
});


Example: http://jsfiddle.net/hY5Wt/

Instead of two arrays, you could have one array of objects. Each object would have a label and index: {label:"First", idx:1}. The autocomplete will use the label to display and on select event, you can access ui.item.idx to get the identifier/index.

$( ".selector" ).autocomplete({
   source: [{label:"First", idx:1},
            {label:"Second", idx:2},
            {label:"Third", idx:3}],
   select: function(event, ui) { alert(ui.item.idx); }
});

You link to an autocomplete plugin, but your code looks like you are using jQuery UI.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜