最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How search into options of select tag html without plugin - Stack Overflow

programmeradmin5浏览0评论

I made select tag with html which contain all the names of the countries and I want to search into their values with search bar without any plugins or add-on is that possible ?

I made select tag with html which contain all the names of the countries and I want to search into their values with search bar without any plugins or add-on is that possible ?

Share Improve this question asked Dec 30, 2014 at 22:42 MaroxtnMaroxtn 6934 gold badges8 silver badges15 bronze badges 9
  • You should post the code you have already or an analog example. – DylanH Commented Dec 30, 2014 at 22:45
  • I don't see no reseon for the vote down the code will be too long more than 100 line 190 countries will be too much for a single page – Maroxtn Commented Dec 30, 2014 at 22:46
  • By default you should be able to start typing and populate the option which begins with the letters you have been typing. – DylanH Commented Dec 30, 2014 at 22:46
  • You can post some example code, by the way I didn't down vote you. – DylanH Commented Dec 30, 2014 at 22:47
  • Would you be open to using JS of any kind, because I think there is no other way to accomplish this client side. – DylanH Commented Dec 30, 2014 at 22:49
 |  Show 4 more comments

3 Answers 3

Reset to default 13

Answer

Yes you can, first, see it in action in this demo, if you like what you see, here's how to do it:

HTML

<input type="search" id="searchBox">
<select id="countries">
    <option value="arg">Argentina</option>
    <option value="usa">United States of America</option>
    <option value="som">Somalia</option>
</select>

It's pretty straight forward, a search input and a select with a few options.

JavaScript

searchBox = document.querySelector("#searchBox");
countries = document.querySelector("#countries");
var when = "keyup"; //You can change this to keydown, keypress or change

searchBox.addEventListener("keyup", function (e) {
    var text = e.target.value; 
    var options = countries.options; 
    for (var i = 0; i < options.length; i++) {
        var option = options[i]; 
        var optionText = option.text; 
        var lowerOptionText = optionText.toLowerCase();
        var lowerText = text.toLowerCase(); 
        var regex = new RegExp("^" + text, "i");
        var match = optionText.match(regex); 
        var contains = lowerOptionText.indexOf(lowerText) != -1;
        if (match || contains) {
            option.selected = true;
            return;
        }
        searchBox.selectedIndex = 0;
    }
});

Explanation

First, the variables:

  • searchBox : link to the HTMLElement search input.
  • countries : link to the HTMLElement select.
  • when : event type, I used "keyup" and that means the select will update when you press and lift a key in the searchBox.
  • text, lowerText : The value of the searchBox (in other words, the input text). The second one equals the first but lowercased for case insensitive testing.
  • options : The select options objects.
  • optionText, lowerOptionText : The text of the option object (ej. "Argentina") and the other one is the lower version for case insensitive testing (ej. "argentina")
  • regex : It's a RegExp Object, a regular expression, basically what it does is it tests (case insensitive, because of the 'i' in the second parameter) wether the some string begins with some value, in this case, the value would be the input text.
  • match : It executes the RegExp Object agains the option's text, that means it will test if the inputted text is the same as the beggining of the option's text.
  • contains : It checks if the option's text contains the inputted text.

Few, that was a lot, so, why do we need 2 tests? Because there are two possibilities for selection with searchBox, one is that when you start typing "Unit.." it should match "United States of America"(regexp), and the other one is that you just type "america" and it should also match "United States of America"(contains)

So, it checks for both tests, and if either one is true it will select that option. (It will also return so that it doesn't continue executing code)

By default, if no test is true, it will select the first element of the select.

Hope that helps :)

If you must not use a plugin or third party script, you could create an array to populate the options and the search through the array using inarray http://api.jquery.com/jquery.inarray/ you would then need to have a method to select the result and use iterator value to tie it back to the corresponding select option.

Also there is this post: Search the options of a select, find the value, add selected to it and write it's html text on a div

Thank you @undefined

In your code instead of making it selected i want to disabled it like display none.

But display: none not working in IE11 

What I did is disabled the un matched options and the hide them.
After this I have sorted the options to show only enabled options on top.
The code I have written is pasted below - please try to understand the logic I hope it will work 

to disabled the options use


  $("#addselect option")attr('disabled', 'disabled').hide

                     and to again enable it use

                    $("#addselect option").removeAttr('disabled').show();

sort by disabled options. 

$("#addselect option").each(function (i, val) {
                if ($(this)[i].disabled) {
                    moveDown("selectId");
                }
                else {
                    moveUp("selectId");
                }
 }

   function moveUp(selectId) {
            var selectList = document.getElementById(selectId);
            var selectOptions = selectList.getElementsByTagName('option');
            for (var i = 1; i < selectOptions.length; i++) {
                var opt = selectOptions[i];
                if (!opt.disabled) {
                    selectList.removeChild(opt);
                    selectList.insertBefore(opt, selectOptions[i - 1]);
                }
            }
        }

        function moveDown(selectId) {
            var selectList = document.getElementById(selectId);
            var selectOptions = selectList.getElementsByTagName('option');
            for (var i = selectOptions.length - 2; i >= 0; i--) {
                var opt = selectOptions[i];
                if (opt.disabled) {
                    var nextOpt = selectOptions[i + 1];
                    opt = selectList.removeChild(opt);
                    nextOpt = selectList.replaceChild(opt, nextOpt);
                    selectList.insertBefore(nextOpt, opt);
                }
            }
        }
发布评论

评论列表(0)

  1. 暂无评论