Bootstrap typeahead: show different text in box once selected

chris.cavage picture chris.cavage · Mar 31, 2016 · Viewed 10.1k times · Source

I am using bootstrap typeahead to search like this:

 $('.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);

        });
}

 });

The JSON data looks like this:

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

It is working great. When the user starts typing the "label" data is shown in a list under the input. HOWEVER, once the user clicks one of the list items, I want the "value" text to appear in the input text box not all the label info that was searched!

Is this possible?

Here's a fiddle:

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

Answer

davidkonrad picture davidkonrad · Apr 1, 2016

I will strongly recommend you upgrade to https://github.com/bassjobsen/Bootstrap-3-Typeahead It is the exact same good old bootstrap 2.x typeahead, just maintained and bugfixed in its own repository since bootstrap 3.0 skipped the typeahead in favour to typeahead.js (which BTW no longer is maintained at all). This will make life much easier for you.

After that you can skip all the contortions and simply do this :

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

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


Updated per comment. I believe you overcomplicate 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)
    })
  }   
})

should do it. Updated fiddle from the comment below -> http://jsfiddle.net/hwbnhbdd/1/ You can use http://myjson.com/ as AJAX source in fiddles as in the update.