我需要帮助,因为我不知道如何在没有选中复选框的情况下阻止表单提交。
var $form = $('#send-invite-form');
var $checkbox = $('input[class^="invitation-friends"]');
$form.on('submit', function(e) {
$.each($checkbox, function(index, value) {
if (!$(value).is(':checked')) {
alert('Opps! You not select friends.');
e.preventDefault();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="send-invite-form">
<input type="checkbox" class="invitation-friends" value="875" />
<input type="checkbox" class="invitation-friends" value="394" />
<button type="submit">Send</submit>
</form>
代码检查每个复选框。我不想要它。我希望如果选中一个复选框,则可以提交表单。如果没有人检查,保释提交。
请帮忙。
最佳答案
有一种方法可以做到这一点,它比您正在做的要简单得多。没有必要循环。刚刚使用 :checked
伪类选择器获取一组已检查的节点,并检查结果节点集的 .length
。如果 .length
为 0
,则未选中任何复选框。
$( '#send-invite-form' ).on('submit', function(e) {
if($( 'input[class^="invitation-friends"]:checked' ).length === 0) {
alert( 'Oops! You not select friends.' );
e.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="send-invite-form">
<input type="checkbox" class="invitation-friends" value="875" />
<input type="checkbox" class="invitation-friends" value="394" />
<button type="submit">Send</submit>
</form>
关于javascript - 如果没有一个复选框被选中,则阻止表单提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47329938/