How to make jQuery autocomplete that passes identifier, not name?

I was looking for jQuery UI autocomplete because I needed on <input /> , but the problem is that I need to pass the identifier of the completed name. Let me explain:

I have an array of names:

 $names = array( array('name' => 'John', id => '1'), array('name' => 'Sarah', id => '2'), array('name' => 'Josh', id => '3) ); 

And then, with AJAX, the input will be autocomplete with a single array name, but then when I submit, I need an identifier, not a name. How can i manage?

Thanks in advance

+6
jquery jquery-ui autocomplete jquery-ui-autocomplete jquery-autocomplete
source share
2 answers

The JQuery UI Autocomplete element can accept a list of search results as a set of Display / Value objects.

From memory, you create a Json object in the following format ...

 [ {label:"Display Name for result 1", value:1}, {label:"Display Name for result 2", value:2}, {label:"Display Name for result 3", value:3} ] 

The label property contains the display text, and the proberty value contains the identifier. These values ​​can be checked when the user selects a search result. The control has a select event that you can listen to.

+13
source share

Your need to keep the identifier in a hidden field.

You can achieve this in the "select" event. http://jqueryui.com/demos/autocomplete/#event-select

This example shows the select event http://jqueryui.com/demos/autocomplete/#custom-data

So, the idea is to do something like this:

  select: function( event, ui ) { $( "#project-id" ).val( ui.item.value ); return false; } 
+8
source share

All Articles