Twitter Bootstrap Typeahead - Id & Label

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

    There's a great tutorial here that explains how to do this: http://tatiyants.com/how-to-use-json-objects-with-twitter-bootstrap-typeahead/ (read my comment on that page if it hasn't been reflected yet in the main part of the post).

    Based on that tutorial, and the JSON you provided, you can do something like this:

    $(':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
            $.each(data, function(i, object) {
                map[object.label] = object;
                objects.push(object.label);
            });
            process(objects);
        },
        updater: function(item) {
            $('hiddenInputElement').val(map[item].id);
            return item;
        }
    });                    
    

提交回复
热议问题