jQuery Tokeninput with “Combobox” functionality?

2019-02-20 15:23发布

问题:

I'm using Loopj Tokeninput plugin and I would like to know if anyone has implemented the jQuery "combobox" functionality in it? or something similar? The scope is to allow for displaying all the data from a local source by clicking an "arrow down" or just by clicking in the input field just like a dropdown menu (but allowing to narrow it down when typing something...). If so, could anyone share how to implement it?

回答1:

Hey there is no method predefined to do that in tokeninput plugin.. However we can alter the plugin itself to achieve what you need. I did some alter to plugin .Do the same change in your jquery.tokenput.js file and see if it works. Open the js file.Search for

var input_box

Now goto .focus(function(){}) part of it and and replace it with this.

if (settings.tokenLimit === null || settings.tokenLimit !== token_count) {
       if (settings.local_data) {
           setTimeout(function() { run_search(''); }, 5);
       } else {
           show_dropdown_hint();
       }

Search for function run_search(query). go to else if part of the function and replace it with below one.

else if (settings.local_data) {
                // Do the search through local data
                var results ;
                if(query==''){
                    results= settings.local_data;
                    }
                    else{
                    results= $.grep(settings.local_data, function(row) {                        
                    return (row[settings.propertyToSearch].toLowerCase().indexOf(query.toLowerCase()) == 0 || row[settings.propertyToSearch].toLowerCase().indexOf(' ' + query.toLowerCase()) > -1);

                });
                }

We are using onfocus of that input box to return the whole list when the box is in focus and query is empty.if query is not empty then it will search for that query.

Additionally, if you wants to show a scrollbar in the search results box, you should modify the css of "div.token-input-dropdown" in the token-input.css file as follows: - Eliminate or Comment: "overflow: hidden;" - Add: "max-height: 150px;" (or whatever max height you want the box to have) - Add: "overflow: auto;"



回答2:

Chosen is exactly what you need.

Chosen is a JavaScript plugin that makes long, unwieldy select boxes much more user-friendly. It is currently available in both jQuery and Prototype flavors.