简体   繁体   English

自动完成jQuery插件:所选数组索引的值

[英]Autocomplete jQuery Plugin : Value of selected array index

How do I get the value of the index position in the array, whose element the user had chosen using the autocomplete? 如何获取数组中索引位置的值,用户使用自动完成功能选择了该元素的元素?

For eg if I enter the array having two elements as the input for the autocomplete plugin: 例如,如果我输入包含两个元素的数组作为自动完成插件的输入:

var arr = [];
arr[0] = "John";
arr[1] = "Paul";

Then, say user selects "Paul", how do I get the value of the selected index "1"? 然后,假设用户选择“ Paul”,如何获得所选索引“ 1”的值?

jQuery way: If your autocompletion source is a plain array (ie not an array of label-value pairs or URL), then you can do jQuery方式:如果您的自动补全源是纯数组(即不是标签值对或URL的数组),则可以执行

$.inArray(ui.item.value,myAutocompleteSource)

eg 例如

  $('.my-autocompletes').autocomplete({ source:['Option1','Option2','Option3'], select: function(event, ui) { alert('Your selected a string with index '+ $.inArray(ui.item.value,$(_self).autocomplete('option','source')) ); } }); 

If the source IS an array of label-value pairs, then you can do 如果源是标签-值对的数组,则可以执行

var index = -1;
$(_self).autocomplete('option','source')).each(function(idx) { 
       if (this.label == ui.item.label) { index=idx; return false; }
});
alert('You selected a string with index '+index);

Of course, $(_self).autocomplete('option','source')) can be replaced with a direct reference to the source of autocomplete items. 当然, $(_self).autocomplete('option','source'))可以替换为对自动完成项来源的直接引用。

As I understand your question, you could just do something like 据我了解,您可以执行以下操作

function FindIndex( arr, searchValue ){
    for( var i = 0; i < arr.length; ++i ){
        if( arr[i] === searchValue ){
            return i;
        }
     }
 }

这个参考http://docs.jquery.com/Attributes/val#val表示您可以使用如下选择器:

$('#selection option:selected')....
var arr = [];
arr[0] = "John";
arr[1] = "Paul";
...
//user selects something
//assuming select value now is in an input field
var index = jQuery.inArray($("input#yourselector").val(), arr);
if (index > -1)
    alert(index);
else
    alert("value not found in autocomplete array");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM