There are a few problems with validating a checkbox with a jQuery. Validation is with the following code. But the problem is – every time I click the submit button, it is repeated. How do I stop it?
-
I want to remove the validation error whenever I click on the checkbox.
-
The user has to select Atlist One or two checkboxes, how to apply this condition?
$('form.checkout').on('submit', function () {
if (!$('input:checkbox').is(':checked')) {
$("input:checkbox").parent().after("<span class='error'>This field requerd....</span>");
}
else {
$("input:checkbox").parent().next(".error").remove();
}
});
<p id="checkout_terms">
<label class="label-for-checkbox">
<input type="checkbox" name="terms" />
<span class="woocommerce-terms-and-conditions-checkbox-text">I have read and agree to the website terms and conditions</span>
</label>
<input type="hidden" name="terms-field" value="1" />
</p>
2
Answers
Remove the error every time, and only add it back if the checkbox isn’t checked. You don’t need an if/else condition.
JSFiddle here
You can follow below code where you can read the number of checked checkboxes and show or hide error accordingly.
Instead of submitting form and validating, use button click event and submit form when no error.