Javascript 如何检查选择框中是否存在值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3879164/
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
How to check if a value exist in select box
提问by Black Rider
Is there any method other than running a for loop to check if a value exists in select box using JavaScript
?
除了运行 for 循环来检查选择框中是否存在值之外,还有其他方法JavaScript
吗?
I am looking for something like document.getElementById('selbox').valueExists('myval');
我正在寻找类似的东西 document.getElementById('selbox').valueExists('myval');
回答by Andreas
You can't extend the methods the select
-element has. So there will not be a solution without an extra function to check for the existence of a value in a select
.
您不能扩展select
-element 具有的方法。因此,如果没有额外的函数来检查 a 中值的存在,就不会有解决方案select
。
A "solution" without a loop could be the following...
没有循环的“解决方案”可能如下...
function SelectHasValue(select, value) {
obj = document.getElementById(select);
if (obj !== null) {
return (obj.innerHTML.indexOf('value="' + value + '"') > -1);
} else {
return false;
}
}
回答by min
with ecma6:
使用 ecma6:
let option = document.getElementById('selbox').querySelector('[value="' + my_value + '"]');
this will find the first element that contains the attribute value="my_value".
这将找到包含属性 value="my_value" 的第一个元素。
PS: sorry by my spanglish :)
PS:对不起,我的西班牙语:)
回答by buttonpol
this worked for me when the page load values from post parameters, so if value is not present on select, alert the user; else, go on (or alert):
当页面从帖子参数加载值时,这对我有用,因此如果选择时不存在值,请提醒用户;否则,继续(或警告):
document.getElementById('your_select_id').value = target_value;
if (document.getElementById('your_select_id').value !== target_value ){
alert('This value is not in Select');
return;
}
回答by elaine
if(!$('#select-box').find("option:contains('" + thevalue + "')").length){
//do stuff
}
回答by Haim Evgi
you can do it with jquery
你可以用 jquery 做到
Use the Attribute Equals Selector
使用属性等于选择器
see in
见
Check if value is in select list with JQuery
in javascript you can run like
在javascript中你可以像
for (var i=0; i<document.getElementById('mySelect').options.length; i++)
{
if (document.getElementById('mySelect').options[i].text == seachtext)
{
alert('found');
break;
}
}