Twitter Bootstrap Typeahead - Id & Label

前端 未结 10 2169
情书的邮戳
情书的邮戳 2020-12-12 13:06

I\'m using Bootstrap 2.1.1 and jQuery 1.8.1 and trying to use Typeahead\'s functionality.

I try to display a label and use an id li

10条回答
  •  被撕碎了的回忆
    2020-12-12 13:37

    Here is an encapsulated solution. This solution allows you have more than one typeahead on the same page.

    This is a modified version of #13279176 Gerbus answer.

    $('.make-me-typeahead').typeahead({
        source: function (query) {
            var self = this;
            self.map = {};
            var items = [];
    
            var data = [
                {"id": 1, "label": "machin"},
                {"id": 2, "label": "truc"}
            ];
    
            $.each(data, function (i, item) {
                self.map[item.label] = item;
                items.push(item.label)
            });
    
            return items;
        },
    
        updater: function (item) {
            var selectedItem = this.map[item];
            this.$element.data('selected', selectedItem);
            return item;
        }
    });
    

    Now when you need get the key of the current selected item you just need do $('.make-me-typeahead').data('selected')

提交回复
热议问题