SBB
SBB

Reputation: 8970

Bootstrap typeahead add value to hidden field

I am using typeahead on my user database and everything seems to work fine. However, the search I am performing on is the last name of a member.

What I am trying to do is once a user is clicked on, instead of using the last name they entered into the field, I want to have it add the users ID to the field instead.

Is there a way to go about doing this?

$('input.query').typeahead({
    name: 'query',
    value: 'lastName',
    remote: 'jsonUser.php?query=%QUERY',
    minLength: 3,
    template: ["<div class='typeahead_wrapper'>", 
                "<img class='typeahead_photo' src='http://localhost/iwebimage.axd?qid={{qid}}'/>", 
                "<div class='typeahead_labels'>", 
                "<div class='typeahead_primary'>{{firstName}} {{lastName}} <small>({{ntid}})</small></div>", 
                "<div class='typeahead_secondary'>{{department}}</div>", 
                "</div>", 
                "</div>", ].join(''),

    engine: Hogan,
    limit: 8,
    valueKey: 'lastName'
});

UPDATE:

The JSON response contains the ID of the user, just not sure how to have the plugin use another value as the final value rather then what you are searching.

Upvotes: 1

Views: 5136

Answers (3)

roo2
roo2

Reputation: 6071

This is what worked for him:

  $('input.query').on('typeahead:selected', function (e, datum) {   

     console.log(datum['empID']); 
  });

I also found Bootstrap Typeahead updater not working which recommends the same

NOTE: twitter are deprecating bootstrap/typhead and recommend that you use https://github.com/twitter/typeahead.js with bootstrap 3

Upvotes: 2

roo2
roo2

Reputation: 6071

EDIT: bootstrap 3 no-longer supports updater. this answer only works for bootstrap 2 typeahead

Overwrite the updater function. and add data-provide="typeahead" to the input

 $('input.query').typeahead({
     updater: function(item) {
        //item the json object that the user selected
        return item.id; // set input's value to item.id
      },
      //....
 )};

Html

<input class="query" data-provide="typeahead" />

Upvotes: 0

Dhaulagiri
Dhaulagiri

Reputation: 3291

Add valueKey: 'empID' to your typeahead parameters and that will be the value put into the search box after you select an item from the typeahead

Upvotes: 0

Related Questions