jquerytypeahead

Search using only values from key-value pair with jquery-typeahead


I'm using jquery-typeahead and my json looks like the following:

{
  field_111: "Some text",
  field_123: "Example text 2",
  field_134: "Text 123"
}

When user types something I want the value to be shown and the key will be a hidden field. I seem to only be able to either have a known key or a non-key/value pair array. The below code is a start but won't show the value from the data source.

$('.testinput').typeahead({
order: "desc",
limit: 5,
hint: true,
highlight: true,
minLength: 1,
autocomplete: "on",
cancelButton: true,
source: {
  data: [{
    field_111: "Some text",
    field_123: "Example text 2",
    field_134: "Text 123"
  }]
},
callback: {
  onInit: function(node) {
    console.log('Typeahead Initiated on ' + node.selector);
  },
  onSearch: function (node, form, item, event) {
    console.log(item);
  }
}
});

Solution

  • I created a function to change the json structure that was supported by typeahead like the following:

      $.each(oldJsonStructure, function(key, value) {
        newJsonStructure.push({ id:key, name:value });
      });
    

    I altered the typeahead options with the following to display the id and name fields:

    $('.testinput').typeahead({
    order: "desc",
    limit: 5,
    hint: true,
    highlight: true,
    minLength: 1,
    autocomplete: "on",
    cancelButton: true,
    display: ['id', 'name']
    source: {
      newJsonStructure
    },
    callback: {
      onSearch: function (node, form, item, event) {
        console.log(item);
      }
    }
    });