javascript 如何在没有插件的情况下搜索选择标签 html 的选项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27713621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 07:52:21  来源:igfitidea点击:

How search into options of select tag html without plugin

javascripthtml

提问by Maroxtn

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 ?

我用包含所有国家/地区名称的 html 制作了选择标签,我想使用搜索栏搜索它们的值,而无需任何插件或附加组件,这可能吗?

回答by undefined

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

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

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 HTMLElementsearch input.
  • countries: link to the HTMLElementselect.
  • 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 Objectagains 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.
  • searchBox:链接到HTMLElement搜索输入。
  • 国家:链接到HTMLElement选择。
  • when:事件类型,我使用了“keyup”,这意味着当您按下并提起搜索框中的某个键时,选择将更新。
  • text,lowerTextsearchBox的值(换句话说,输入文本)。第二个等于第一个,但小写用于不区分大小写的测试。
  • 选项:选择选项objects
  • optionText, lowerOptionText: 选项的文本object(ej.“Argentina”),另一个是不区分大小写测试的低版本(ej.“argentina”)
  • regex:它是一个RegExp Object正则表达式,基本上它的作用是测试(不区分大小写,因为第二个参数中的“i”)某个字符串是否以某个值开头,在这种情况下,该值将是输入文本。
  • match:它RegExp Object再次执行选项的文本,这意味着它将测试输入的文本是否与选项文本的开头相同。
  • contains:它检查选项的文本是否包含输入的文本。

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)

很少,那很多,那么,为什么我们需要 2 个测试?因为 searchBox 有两种选择的可能性,一种是当你开始输入“Unit..”时,它应该匹配“United States of America”(regexp),另一种是你只输入“america”,它应该也匹配“美利坚合众国”(包含)

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 :)

希望有帮助:)

回答by DylanH

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.

如果您不能使用插件或第三方脚本,您可以创建一个数组来填充选项并使用 inarray http://api.jquery.com/jquery.inarray/搜索数组,然后您需要有一个方法来选择结果并使用迭代器值将其与相应的选择选项联系起来。

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

还有这篇文章:搜索选择的选项,找到值,将选择添加到它并在 div 上写入它的 html 文本

回答by Namrata S Jain

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);
                }
            }
        }