Bootstrap typeahead: display other text in the field after selection

I use bootstrap typeahead to search as follows:

$('.lookup').typeahead({ source: function (query, process) { return $.getJSON( 'json_autocomplete.php',{ query: query }, function (data) { var newData = []; $.each(data, function(){ newData.push(this.label); //populate hidden field with id $('#contact_id').val(this.id); }); return process(newData); }); } }); 

JSON data is as follows:

  [{"label":"Contact: Jeff Busch-> Busch, Jeff: 1975-11-24","value":"Busch, Jeff","id":"2096"}, ... 

It works great. When the user begins to enter β€œtag” data, it is displayed in the list below the input. HOWEVER, as soon as the user clicks on one of the elements of the list, I want the text "value" to be displayed in the input text field not in all programmed labels!

Is it possible?

Here's the fiddle:

http://jsfiddle.net/michels287/qdgo651h/

+5
source share
2 answers

I highly recommend you go to https://github.com/bassjobsen/Bootstrap-3-Typeahead . This is the same old old typeahead 2.x boot file, just maintained and fixed in its own repository, since bootstrap 3.0 skipped typeahead in favor of typeahead.js (which BTW is no longer supported at all). It will make life a lot easier for you.

After that, you can skip all the distortions and just do it:

 $('#contact').typeahead( { source: jsonData, displayText: function(item) { return item.label }, afterSelect: function(item) { this.$element[0].value = item.value } }) 

updated script -> http://jsfiddle.net/qdgo651h/1/


Updated for comment. I believe that you are compromising the source part

 $('.lookup').typeahead({ displayText: function(item) { return item.label }, afterSelect: function(item) { this.$element[0].value = item.value }, source: function (query, process) { return $.getJSON('json_autocomplete.php', { query: query }, function(data) { process(data) }) } }) 

must do it. Updated fiddle from comment below β†’ http://jsfiddle.net/hwbnhbdd/1/ You can use http://myjson.com/ as an AJAX source in scripts, as in the update.

+8
source

Just return the data to the update event as follows:

  updater: function (item) { $('#id').val(map[item].id); //Here we return the text to display on the input control return map[item].autocomplete; }, 
0
source

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


All Articles