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

2

7

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

Absorptivity answered 6/12, 2010 at 11:32 Comment(0)
T
14

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.

Tahmosh answered 6/12, 2010 at 11:47 Comment(0)
S
8

Your need to save the id into a hidden field.

You can achieve that on 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;
        }
Sharpie answered 6/12, 2010 at 11:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.