jira
jira

Reputation: 3944

jquery autocomplete - get selected item

I have an autocomplete field using local JSON data.

 $( "#tags" ).autocomplete({ 
 source: get_items,  
 minLength: 2,  
 dataType: 'json'

 });

 function get_items(request, callback) {  
   var result = new Array;

   var myregexp = new RegExp('^' + request.term, "i");

   for(var i = 0; i < keywords.length; i++) {
     if (myregexp.test(keywords[i].name)) {
       var item = { label: keywords[i].name,
                    id   : keywords[i].id
                    };
       result.push(item);
     }

   }

   callback(result);
   return result;
 }

What I cannot find out (I did RTFM), is how can I get id of the selected item from somewhere "outside". I mean not from the autocomplete callbacks, but from some unrelated function somewhere else. Hope, I'm clean.

something like:

 function i_do_something_with_the_selected_item() {
      var seleted_id = $( "#tags" ).get_selected_id();
   if (typeof selected_id === 'undefined') {
     // nothing selected - act accordingly

   }   else {    
     // do something with the selected value
    }

 }

Upvotes: 0

Views: 2007

Answers (1)

jAndy
jAndy

Reputation: 236202

The jQuery autocomplete is intended for autocompletion. It will not memoize what items were selected (that is not its job). That is application logic and is on you.

However, you can access the source array by calling

$( '#tags' ).autocomplete( 'source' );

I guess it would be pretty convinient, to write some property to the selected item on the autocompleteselect event. Now you can read that value everywhere else in your code.

Upvotes: 1

Related Questions