我有这段代码,但它似乎没有返回 true。警报总是出现。任何想法(不需要创建一个 var 来存储已选中的复选框,因为这看起来有点 hacky)。
谢谢。
$("#form").submit(function(e) {
$('input[type=checkbox]').each(function () {
if(this.checked){
return true;
}
});
alert("Please select at least one to upgrade.");
return false;
});
最佳答案
您不需要执行循环来确定是否选中复选框。 :checked
选择器过滤掉所有未检查的内容。然后你可以使用$.length
获取已检查输入的计数。
$("#form").submit(function(e) {
if(!$('input[type=checkbox]:checked').length) {
alert("Please select at least one to upgrade.");
//stop the form from submitting
return false;
}
return true;
});
此外,使用你的方法,一个小的改变应该可以使这个工作
$("#form").submit(function(e) {
$('input[type=checkbox]').each(function () {
if($(this).is(':checked')){
return true;
}
});
alert("Please select at least one to upgrade.");
return false;
});
我认为您可能只是错过了 this
周围的 $()
关于Jquery 停止表单提交,除非选中复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4795872/