[英]Submit form only if at least one checkbox is checked using javascript
I have the following form: https://expogr.com/bankexpokenya/advertise.php我有以下表格: https : //expogr.com/bankexpokenya/advertise.php
I am filling the details of the form and clicking on the submit button.我正在填写表单的详细信息并单击提交按钮。 If I have not checked one checkbox, it gives me a message saying "please select any one checkbox" along with the
ok
button.如果我没有选中一个复选框,它会给我一条消息,说“请选择任何一个复选框”以及“
ok
按钮。 After clicking the ok
button, the form is getting submitted.单击
ok
按钮后,表单将被提交。 For form submission, I have used email method so the form data is sent to the particular emailids.对于表单提交,我使用了电子邮件方法,因此表单数据被发送到特定的 emailids。
I have tried the following code:我尝试了以下代码:
$(document).ready(function(){
$("form").submit(function(){
if ($('input:checkbox').filter(':checked').length < 1){
alert("Please select at least one option from above!");
break;
return false;
}
});
});
But its not working.但它不起作用。
$(document).ready(function(){
$("form").submit(function(){
if ($('input:checkbox').filter(':checked').length < 1){
alert("Please select at least one option from above!");
break;
return false;
}
});
});
The issue is with the break
statement, remove that and your code will work as expected.问题在于
break
语句,删除它,您的代码将按预期工作。 Also, you do not need to use .filter()
separately as you can specify :checked
as part of the selector:此外,您不需要单独使用
.filter()
因为您可以指定:checked
作为选择器的一部分:
$(document).ready(function(){ $("form").submit(function(){ if ($('input:checkbox:checked').length < 1){ alert("Please select at least one option from above!"); return false; } }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form> <input type="checkbox"/>First <input type="checkbox"/>Second <input type="submit" value="Submit"/> </form>
You can also try with Event.preventDefault()
:您也可以尝试使用
Event.preventDefault()
:
$(document).ready(function(){ $("form").submit(function(e){ if ($('input:checkbox:checked').length < 1){ alert("Please select at least one option from above!"); e.preventDefault(); } }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form> <input type="checkbox"/>First <input type="checkbox"/>Second <input type="submit" value="Submit"/> </form>
You can remove the break statement.see the below mentioned code.您可以删除 break 语句。请参阅下面提到的代码。
$(document).ready(function(){
$("form").submit(function(){
if ($('input:checkbox').filter(':checked').length < 1){
alert("Please select at least one option from above!");
return false;
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.