我希望简化此验证代码。
if($('#textbox1').val() != '' && $('#textbox2').val() != '' && $('#textbox3').val() != ''){
$('#myModal').modal('show');
}else {
alert ('textboxes must be empty');
}
我已经将 required
属性添加到每个 textbox
中,但我希望在显示模式之前进行另一次验证。还有其他方法可以简化这个吗?我已经尝试过这种方法了
if($('#textbox1, #textbox2, #textbox3'){
$('#myModal').modal('show');
}else {
alert ('textboxes must be empty');
}
但它只识别第一个 id (textbox1
)。如果其他文本框
为空,它仍会显示模式。
最佳答案
您可以仅按类别和过滤器进行选择
if ($("[required]").filter(function() { return !this.value.length; }).length) {
//stuff is not filled in
} else {
//filled in
}
或者您可以只使用任何 jQuery 验证库。
HTML:
<input type="text" required />
<input type="text" required />
<input type="text" required />
JavaScript:
$("[required]").on("change", function() {
var color;
if ($("[required]").filter(function() { return !this.value.length; }).length) {
color = "red";
} else {
color = "green";
}
$("body").css("background-color", color);
}).eq(0).trigger("change");
关于javascript - 简化 Jquery 中不同 id 的验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25173040/