如果选中某个复选框,我正在尝试阻止表单提交并触发范围错误。如果选中复选框3,4和6。请注意,每个复选框组都有两条错误消息。
<form action="" method="" role="form" name="form1">
<span id="sprycheckbox1">
<span class="checkbox-error hide">
Your answer contains a wrong selection. Please try again.
</span>
<input type="checkbox" name="checkbox" id="checkbox1">
<label for="checkbox">checkbox1</label><br>
<input type="checkbox" name="checkbox" id="checkbox2">
<label for="checkbox">checkbox2</label><br>
<input type="checkbox" name="checkbox" id="checkbox3">
<label for="checkbox">checkbox3</label><br>
<input type="checkbox" name="checkbox" id="checkbox4">
<label for="checkbox">checkbox4</label><br>
</span>
<span id="sprycheckbox2">
<span class="checkbox-error hide">
Your answer contains a wrong selection. Please try again.
</span>
<input type="checkbox" name="checkbox" id="checkbox5">
<label for="checkbox">checkbox5</label><br>
<input type="checkbox" name="checkbox" id="checkbox6">
<label for="checkbox">checkbox6</label><br>
<input type="checkbox" name="checkbox" id="checkbox7">
<label for="checkbox">checkbox7</label><br>
<input type="checkbox" name="checkbox" id="checkbox8">
<label for="checkbox">checkbox8</label><br>
<input type="checkbox" name="checkbox" id="checkbox9">
<label for="checkbox">checkbox9</label><br>
</span>
<br><br>
<button name="submit" type="submit" class="btn btn-natio general-btn-extra-padding" onclick="validateSubmission()">NEXT</button></form>
function validateSubmission() {
var checkboxSelected = document.getElementById('checkbox6').checked;
if(checkboxSelected) {
$('span.checkbox-error').removeClass('hide');
} else {
$('span.checkbox-error').addClass('hide');
// submit your form here like below
var forms = document.getElementsByName('form1');
forms[0].submit();
}
}
答案 0 :(得分:0)
您可以使用表单即将提交时将发生的表单的onsubmit事件,只要在出现错误时返回false。
<button name="submit" type="submit" class="btn btn-natio general-btn-extra-padding" onsubmit="return validateSubmission()">NEXT</button>
function validateSubmission() {
int isValid = false;
// Validation Logic
if(!isValid) {
// Show Error Message
return false;
}
}
答案 1 :(得分:0)
试试这个
function validateSubmission() {
if($('input[type=checkbox]:checked').length) {
$('span.checkbox-error').removeClass('hide');
alert("Please select at least one to upgrade.");
//stop the form from submitting
return false;
}
else {
$('span.checkbox-error').addClass('hide');
// submit your form here like below
return true;
}
});