Pregunta

Bootstrap just implemented a neat autocomplete feature called typeahead. I am having trouble getting the appropriate value for the text input.

For instance, I might have the following:

$('input').on('change', function(){
    console.log($(this).val());
});

This does not appear to capture the selected value. Does anyone know how to get the selected value using typeahead with Bootstrap?

¿Fue útil?

Solución

$('#autocomplete').on('typeahead:selected', function (e, datum) {
    console.log(datum);
});
$('#autocomplete').on('typeahead:cursorchanged', function (e, datum) {
    console.log(datum);
});

Seems Typeahead changed listeners and usages are not well documented. You can use these listeners.

UPDATE

Event name was changed to typeahead:select in later versions.

Otros consejos

You're looking at it from the wrong angle. Bootstrap's typeahead method provides an option which allows you to pass a callback function that receives the selected value as the argument. Below is a condensed example illustrating just this one argument.

$('#typeaheadID').typeahead({
    updater: function(selection){
        console.log("You selected: " + selection)
    }
})

cheers! documentation refernece

I'm working with this and I'm having the same issue right now. I'm planning to solve it with this pretty fork

https://gist.github.com/1891669

And I did it with a callback:

  $('.typeahead').typeahead({
    // note that "value" is the default setting for the property option
    source: [{value: 'Charlie'}, {value: 'Gudbergur'}, ...],
    onselect: function(obj) { console.log(obj) }
  })

Hope it helps you too.

If you only had 1 on the page you could try $('ul.typeahead li.active').data('value'); but you may have have issues if there's more than 1 on a page.

I wonder if there's a reason why the input value is not set?

$('#myselector').typeahead({
itemSelected:function(data,value,text){
   console.log(data)
    alert('value is'+value);
    alert('text is'+text);
},
//your other stuffs
});

You have to just pass itemSelected in the callback function and it will give you the selected item.

Hope this will work for you.

If you are using another button to work with selected item or need get this item not right after update you can use $("#your_input").next("ul").find("li.active").data("value"); to get your value.

Working for ajax bootstrap typeahead.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top