Get selected items value for Bootstrap's typeahead

前端 未结 6 1855
萌比男神i
萌比男神i 2021-01-01 20:17

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

相关标签:
6条回答
  • 2021-01-01 20:21

    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.

    0 讨论(0)
  • 2021-01-01 20:30
    $('#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.

    0 讨论(0)
  • 2021-01-01 20:32
    $('#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.

    0 讨论(0)
  • 2021-01-01 20:33

    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

    0 讨论(0)
  • 2021-01-01 20:34

    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?

    0 讨论(0)
  • 2021-01-01 20:35

    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.

    0 讨论(0)
提交回复
热议问题