Customize jquery autocomplete result

I am using 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 very well. When I type "a", the list of operations (from the database) begins with this list. What I would like to do is add a custom parameter (activity identifier) ​​to the result.

Because when the user selects the action later, I will have to redo the sql search to get the activity identifier ...

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

thanks

+6
source share
3 answers

If your index.php / ajax / autosuggest page returns an array of JSON objects with two keys "label" and "value" (instead of an array of strings), the jQuery UI Autocomplete plugin using the label "to display in the autocomplete list, but actually gives 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 did not test thist, just found it here: http://www.petefreitag.com/item/756.cfm

+3
source

The way Wesley is described is what we are using now.

By returning both the label and id in our JSON objects, we can capture this identifier the way we want (in our case, storing it in hidden input), while the label is used to show the users whose record is selected.

Basic example: http://jsfiddle.net/NLK5p/4/

+1
source

What data source are you using? I highly recommend the freebase free database with over 12 million votes and provides web services to automatically launch (including js functions) in a wide variety of areas (jobs, sports, actors, films or whatever you want) ... not everyone knows about it, but google bought the project last year (it is still available and free), so it should become a promising web service for data sources.

0
source

Source: https://habr.com/ru/post/889765/


All Articles