1

How 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"?

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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;
        }
     }
 }

1 Comment

Can also do that with the jQuery find() method. docs.jquery.com/Traversing/find#expr
0

This ref http://docs.jquery.com/Attributes/val#val says you can use a selector like so:

$('#selection option:selected')....

Comments

0
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");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.