gpt4 book ai didi

Jquery 停止表单提交,除非选中复选框

转载 作者:行者123 更新时间:2023-12-03 22:17:20 26 4
gpt4 key购买 nike

我有这段代码,但它似乎没有返回 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com