Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customize jquery autocomplete result

I'm using the jQuery autocomplete with a remote data source

    $( "input#searchbar" ).autocomplete({
        source: function( request, response ) {
            $.ajax({type: "post",
            mode: "abort",
            dataType: 'json',
            url: 'index.php/ajax/autosuggest',
            data: { term: $("#searchbar").val()},
            success: function(data) {

                response(data);
            }
        });
    },
    select: function(e, ui) {
        //Refresh pros
        if (map){
            mouseUpOnTheMap();
        }
    }
});

It works really well. When i type "a" there is a list of activity (fetched from a database) starting with that are listed. What i would like to do it's add a custom parametre (the ID of the activity) in the result.

Because when a user select an activity later I will have to "re-do" a sql search to get the ID of the activity...

So is there a way to include the activity id in the returned JSON from the autocomplete ?

THanks

like image 941
Fazoulette Avatar asked Jun 04 '11 12:06

Fazoulette


1 Answers

If your index.php/ajax/autosuggest page returns an array of JSON objects with two keys of "label" and "value" (instead of an array of strings), the the jQuery UI Autocomplete plugin with use the "label" key to display in the autocomplete list, but actually give you the JSON object that was selected in the select event. Then you can reference the value of the object.

$( "input#searchbar" ).autocomplete({
        source: function( request, response ) {
            $.ajax({type: "post",
            mode: "abort",
            dataType: 'json',
            url: 'index.php/ajax/autosuggest',
            data: { term: $("#searchbar").val()},
            success: function(data) {
                //data assumes [{label: "result 1", value: 1}, {label: "result 2", value: 2}];
                response(data);
            }
        });
    },
    select: function(e, ui) {
        var selectedItem = ui.item;
        var id = selectedItem.value;
        var label = selectedItem.label;

        //Refresh pros
        if (map){
            mouseUpOnTheMap();
        }
    }
});

I haven't tested thist, just found it here: http://www.petefreitag.com/item/756.cfm

like image 164
WesleyJohnson Avatar answered Oct 17 '22 12:10

WesleyJohnson