简体   繁体   English

使用JavaScript检查多重选择框中是否已存在选项

[英]Check if an option already exists in a multi select box using JavaScript

My question is same as this - How can I check whether a option already exist in select by JQuery 我的问题与此相同- 如何检查JQuery select中是否已经存在选项

Although I want to know how it can be done using JavaScript rather than using jQuery. 虽然我想知道如何使用JavaScript而不是jQuery来完成。 I've tried using the indexOf() , === among other things, but I'm not sure if my approach is correct. 我尝试过使用indexOf()===等等,但是我不确定我的方法是否正确。

PS : If you're marking it as a duplicate, do link me with the question that has the answer in JavaScript. PS:如果您将其标记为重复项,请将我与JavaScript中具有答案的问题联系起来。 Thank you. 谢谢。

Also, reasons for down voting are welcome. 此外,欢迎投反对票的理由。

My approach : 我的方法:

var foldersList = document.getElementById("folders");
    for(var i=0; i<foldersList.length; i++)
    {
       if(!(foldersList.options[i].value.indexOf("someValue") === -1))
       {
             //do something
       }
    }

You could use document.querySelectorAll : 您可以使用document.querySelectorAll

document.querySelectorAll('#yourSelect option[value="yourValue"]').length > 0

Thats the same as: 就是这样:

$("#yourSelect option[value='yourValue']").length > 0;

The simple way, supported even by the most antique browsers: 最古老的浏览器都支持的简单方法:

function selectHasOption(select, value)
{
    for (var i = 0, len = select.options.length; i != len; ++i) {
        if (select.options[i].value == value) {
            return true;
        }
    }
    return false;
}

And this is the expression: 这是表达式:

selectHasOption(document.getElementById('folders'), 'someValue')
var yourSelect = document.getElementById("yourSelect");
for (i = 0; i < yourSelect.length; ++i) {
   if (yourSelect.options[i].value == "someValue") {
      alert("someValue is available");
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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