【问题标题】:Getting the Index of the selected item in jquery auto complete在jquery自动完成中获取所选项目的索引
【发布时间】:2011-08-25 00:10:24
【问题描述】:

我用的是jQuery autocomplete,如下:

从我的 PHP 文件中,我得到了 json 编码的数组 - 一个用于 ids,一个用于名称。

我用名字填充自动完成。在select 函数中,我能够正确提醒 所选项目,但我无法获取所选项目的索引。如何获得?

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

        }
    });
});

【问题讨论】:

    标签: javascript jquery autocomplete


    【解决方案1】:

    示例:http://jsfiddle.net/hY5Wt/

    你可以有一个对象数组,而不是两个数组。每个对象都有一个标签和索引:{label:"First", idx:1}。自动完成将使用标签显示,在选择事件时,您可以访问 ui.item.idx 以获取标识符/索引。

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

    您链接到一个自动完成插件,但您的代码看起来像是在使用 jQuery UI。

    【讨论】:

    • 是否可以在文本框中只显示一个字段? (不一定是标签字段)?
    猜你喜欢
    • 2011-09-19
    • 2011-12-07
    • 1970-01-01
    • 2017-04-28
    • 2013-11-09
    • 2014-11-05
    • 2011-09-05
    • 2013-06-25
    • 2012-11-13
    相关资源
    最近更新 更多