多个选择框重复值比较 [英] Several select box duplicate values compare
问题描述
我想比较选择框中选择的选项值,如果选择框中有重复的值,我想显示警报:
I want to compare select boxes selected option value, and if there are duplicate values in the select boxes I want to show alert:
alert("Duplicate value!");
这是我的代码:
<select class="examSelect">
<option value="one">ba</opion>
<option value="two">woo</opion>
<option value="three">coo</opion>
<option value="four">po</opion>
</select>
<select class="examSelect">
<option value="one">ba</opion>
<option value="two">woo</opion>
<option value="three">coo</opion>
<option value="four">po</opion>
</select>
<select class="examSelect">
<option value="one">ba</opion>
<option value="two">woo</opion>
<option value="three">coo</opion>
<option value="four">po</opion>
</select>
推荐答案
这是一种使用对象属性的方法.它会在第一次看到该属性时创建该属性,如果第二次看到相同的值,它将中断并发出警报.
Here's an approach that uses object properties. It creates the property the first time it sees it, and if it sees that same value a second time, it breaks out and alerts.
可以很容易地修改它,以保持重复的数量,例如您为3个不同的选项输入了'woo'!"
This could easily be modified to maintain a count of duplicates, e.g. "You entered 'woo' for 3 different selections!"
由于它使用jQuery each()
来调查每个匹配的下拉列表,因此无需修改即可扩展HTML中的其他选择框.
It's also extensible for additional select boxes in your HTML with no modification since it's using jQuery each()
to survey every matching dropdown.
function checkit() {
var checker = {};
$(".examSelect").each(function() {
var selection = $(this).val();
if ( checker[selection] ) {
//if the property is defined, then we've already encountered this value
alert("Duplicate(s) detected!");
return false;
} else {
//first time we've seen this value, so let's define a property for it
checker[selection] = true;
}
});
console.log(checker); //remove this in production
}
https://jsfiddle.net/y5y9uy5v/2/
这篇关于多个选择框重复值比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!