Set selected value of typeahead

gpasse picture gpasse · Jun 24, 2013 · Viewed 30.1k times · Source

I am using the twitter bootstrap typeahead.

I have customized the typehead so I can select a pair value/label

$.each(data.medicines,function(index,values){

    _med=new Object()
    _med.value=values.LYF
    _med.id=values.LYF_NUMER
    _medicines.push(_med)

})

//Fill typeahead with data
$('.typeahead').typeahead({
    // note that "value" is the default setting for the property option
    source:_medicines,
    onselect: function(obj) { showdetails(obj) }
})

How can I set the selected value using Javascript ?

For exemple $("#mytypehead").val(43);

Answer

Matt Ball picture Matt Ball · Jun 24, 2013

According to the typeahead.js documentation on GitHub (which is much more detailed than the bootstrap-typeahead.js docs in Twitter Bootstrap):

jQuery#typeahead('setQuery', query)

Sets the current query of the typeahead. This is always preferable to using $("input.typeahead").val(query), which will result in unexpected behavior. To clear the query, simply set it to an empty string.

2016 Update (setQuery does not exist anymore) :

jQuery#typeahead('val', val) Sets the value of the typeahead. This should be used in place of jQuery#val.

$('.typeahead').typeahead('val', myVal);

New documentation here