Blease
Blease

Reputation: 1420

Update a hidden input field with Typeahead.js and JSON key values

I have a working typeahead element on a page which fetches data from a remote url which returns a JSON string such as this [{"id":"1","name":"Ben"},{"id":"2","name":"Josh"}].

I wish for a hidden field to be updated with the respective ID number. My current typeahead setup is as follows

$('.typeahead').typeahead({
name: 'typeahead',
remote: {
  url: 'backend/clients.php?query=%QUERY',
  filter: function(data) {
    var resultList = data.map(function(item) {
      return item.name;
    });
    return resultList;
  }
}
});

Upvotes: 3

Views: 3464

Answers (1)

Pranav C Balan
Pranav C Balan

Reputation: 115222

You can bind handler for custom event typeahead:select which fired when a suggestion is selected. The event handler will be invoked with 2 arguments: the jQuery event object and the suggestion object that was selected. Based on the selected value update the hidden field.

var resultList, d;
$('.typeahead').typeahead({    
    name: 'typeahead',
    remote: {
      url: 'backend/clients.php?query=%QUERY',
      filter: function(data) {
        d = data;
        resultList = data.map(function(item) {
          return item.name;
        });
        return resultList;
      }
    }    
}).on('typeahead:select', function(ev, suggestion) {
     $('#hidden-input').val(suggestion.id);
    // $('#hidden-input').val(d[resultList.indexOf(suggestion)].id);
});

Ref : https://github.com/twitter/typeahead.js/blob/master/doc/jquery_typeahead.md#custom-events

Upvotes: 4

Related Questions