Twitter Bootstrap Typeahead - Id & Label

前端 未结 10 2143
情书的邮戳
情书的邮戳 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:44

    To clarify what I was saying in my comment. If you wanted multiple type aheads on the same page you need to define each in a function and create a separate map variable for them.

    function initFromField() {
        var map;
        $('#from:input.autocomplete').typeahead({
            source: function(query, process) {
                map = {};
                var data = [{"id":1,"label":"machin"},{"id":2,"label":"truc"}] // Or get your JSON dynamically and load it into this variable
                objects = constructMap(data, map);
                process(objects);
            },
            updater: function(item) {
                $('#hidden-from-input').val(map[item].id);
                return item;
            }
        });
    }
    
    function initToField() {
        var map;
        $('#to:input.autocomplete').typeahead({
            source: function(query, process) {
                objects = [];
                map = {};
                var data = [{"id":1,"label":"machin"},{"id":2,"label":"truc"}] // Or get your JSON dynamically and load it into this variable
                objects = constructMap(data, map);
                process(objects);
            },
            updater: function(item) {
                $('#hidden-to-input').val(map[item].id);
                return item;
            }
        });
    }
    
    function constructMap(data, map) {
        var objects = [];
        $.each(data, function(i, object) {
            map[object.label] = object;
            objects.push(object.label);
        });
        return objects;
    }
    
    $(function initFields() {
        initFromField();
        initToField();
    });
    

    Note how I scoped the map variable inside the two field initialization functions. This is important, it makes sure the same map variable is not used by both input fields.

提交回复
热议问题