我的目标是检查所有 SELECT 元素是否有重复值(无法在 2 个 SELECT 中选择相同的值)
我已经进行了大量搜索,但所有 2 个 SELECT 都无法修复更多
我尝试过的逻辑:
check function(){
declare values array, errorElement array
foreach(select element){ if the selected value exist in the value array(duplicate), add the element to the error element array
else add the value to the value array
}
if no error elements (no duplicated values), remove the error class from all selects
else foreach(select elemnt){
if the select exists in the error element array, set error class
else remove error class
}
}on any select change, call check function
这里是demo
function checkSelects()
{
var errorElements = []; var values = [];
$("select").each(function () {
if ($.inArray($(this).val(), values) !== -1) {
errorElements.push($(this).attr('id'));
} else {
values.push($(this).val());
}
});
if (errorElements.length === 0) {
$("select").each(function () {
$(this).removeClass('error');
});
} else {
$("select").each(function () {
if ($.inArray($(this).attr('id'), errorElements) !== -1) {
$(this).addClass('error');
} else {
$(this).removeClass('error');
}
});
}
}
$(function () {
$("select").change(function () {
checkSelects();
});
});
就功能而言,它工作得非常完美,为重复冲突的一侧设置了错误类。但我想让它更清楚并为双方设置错误类
这是否太过分了?任何指针如何实现这一目标?
这是它的屏幕截图
在 2 个 SELECT 中选择 text1 只会设置后面元素的错误类。
我希望两个文本都显示为红色
最佳答案
像这样使用
function checkSelects() {
var errorElements = [];
var values = [];
$("select").each(function () {
if ($.inArray($(this).val(), values) !== -1) {
errorElements.push($(this).attr('id'));
} else {
values.push($(this).val());
}
});
if (errorElements.length === 0) {
$("select").each(function () {
$(this).removeClass('error');
});
} else {
$("select").each(function () {
if ($.inArray($(this).attr('id'), errorElements) !== -1) {
$(this).addClass('error');
$("select[value="+$(this).val()+"]").addClass('error'); <---- here
} else {
$(this).removeClass('error');
}
});
}
}
艾特
我已经简化了你的代码,你也可以这样使用
function checkSelects() {
$(".error").removeClass("error");
$("select").each(function () {
if ($("select[value=" + $(this).val() + "]").length > 1) {
$("select[value=" + $(this).val() + "]").addClass('error');
}
});
}
$(function () {
$("select").change(function () {
checkSelects();
});
});
<强> Updated Fiddle
关于jquery - 动态检查 SELECT 重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24157590/