简体   繁体   中英

Twitter Bootstrap, Typeahead, images

I'm trying to create Typeahead search with Twitter Bootstrap 2.2.1. I've managed to work with JSON and not strings like this:

$('#search').typeahead({
    minLength: 3,
    source: function (query, process) {
    $.post('@Url.Action(<MySearchAction>, <MyControllerName>)', { Text: query }, function (data) {
            var source = [];
            $.each(data, function (index, value) {
                source.push(JSON.stringify(value));
            });
            process(source);
        });
    },
    updater: function (item) {
        var itemJSON = JSON.parse(item);
        window.location.href = '@Url.Action(<MyDetailsAction>, <MyControllerName>)/' + itemJSON.ID;
    },
    highlighter: function (item) {
        var itemJSON = JSON.parse(item);
        return itemJSON.Name;
    },
});

Now I want to do more

  1. Is it a right way to work with JSON in typeahead?
  2. I want to show different types of objects in drop down - suppose I have Songs and Albums types, I want to show all Songs found then divider and then all Albums found.
  3. I want to show images in dropdown - like covers of Albums.

I've read topic here Allow loading images and custom HTML in typeahead results .
Quote from that topic: "Using a combination of the item and menu options you can specify new templates" , but I still do not get how to do it in a right way.

Thank you.

Since typeahead processes strings with the source function I used those strings as keys to access data.

Somewhat like this

$('#search').typeahead({
    myData: {"key":{image:"image.jpg",description:"lorem blahblah"}},
    source: //Load data in a function
        //add data to myData with the key being the string you would process, 
        //and the value being an object you want to get values from

    highlighter: function(item){
        var item = this.options.myData[item];
        var image = item.image;
        var description = item.description
        return "<img src='"+image+"'>" so on and so forth;
    }

That should get you started.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM