How to get id and value from twitter bootstrap and

2019-06-23 17:40发布

问题:

How to get both id and value from typeahead.js when selecting a suggestion?

I have a json as follows:

[
    {id:1, name:'paul'}, 
    {id:2, name:'jim'}, 
    {id:3, name:'tom'}, 
    {id:4, name:'medor'}, 
    {id:5, name:'janzy'}
]

and i created Bloodhound object as follows:

var bh = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    prefetch: '//localhost/data/names.json',
    identify: function(datum){
        return datum.id;    
    }
});

and i instantiated typeahead as follows:

$('#name').typeahead({"highlight":true}, {
    "name":"name",
    "source":bh,
    "display":"value",
    "limit":10
})

I want to be able to get the id when i submit my form. When i submit the following example, i obtain only the name attribute.

i tried to obtain the id via javascript as follows:

$('#name').bind('typeahead:select', function(ev, suggestion){
    console.log(suggestion);
})

but suggestion contains an object with only text value which i selected

回答1:

You have a couple of options.

I think overriding the identity function may get you what you need. Something like this might get you there:

identify: function(datum){
        return { id: datum.id, value: data.name};    
    }

I use remote for my actual production code and use the filter option to return the display value as well as the key value.

It looks something like this:

remote: {
        url: '/some/url',
        filter: function (data) {
            if (data) {
                return $.map(data, function (object) {
                    return { id: object.id, value: object.name};
                });
            } else {
                return {};
            }
        }
    }

You can also try using the transform function as part of prefetch, which would look something like this:

prefetch: {
        url: '/some/url',
        transform: function (response) {
            if (response) {
                return $.map(response, function (object) {
                    return { id: object.id, value: object.name};
                });
            } else {
                return {};
            }
        }
    }

The documentation (available here) is somewhat helpful, but doesn't do much to show more complicated examples.

I also experimented with the examples (typeahead examples) quite a bit before I finally found my answers.