Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do jQuery autocomplete that passes a id and not a name?

I was looking for jQuery UI Autocomplete because I needed on a <input /> but the problem is that I need to pass the id of the name completed. 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 autocompleted with one name of the array but then, when I submit, I need the id and not the name. How can I manage?

Thanks in advance

like image 952
ipalaus Avatar asked Dec 06 '10 11:12

ipalaus


1 Answers

The JQuery UI Autocomplete control can accept the 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 text to display and the value proberty contains the id. These values can be inspected when a search result is selected by the user. The control has a select event that you can listen for.

like image 118
Andy McCluggage Avatar answered Oct 14 '22 01:10

Andy McCluggage