Ho开发者_StackOverflow中文版w do I get the value of the index position in the array, whose element the user had chosen using the autocomplete?
For e.g. 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"?
jQuery way: If your autocompletion source is a plain array (i.e. not an array of label-value pairs or URL), then you can do
$.inArray(ui.item.value,myAutocompleteSource)
e.g.
$('.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.
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;
}
}
}
This ref http://docs.jquery.com/Attributes/val#val says you can use a selector like so:
$('#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");
精彩评论