skip to Main Content

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?

  1. I want to remove the validation error whenever I click on the checkbox.

  2. The user has to select Atlist One or two checkboxes, how to apply this condition?

enter image description here

$('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


  1. Remove the error every time, and only add it back if the checkbox isn’t checked. You don’t need an if/else condition.

    // Form submission
    $('form.checkout').on('submit', function () {
    
        let valid = true;
    
        // Validate all checkboxes in the form
        $(this).find('input:checkbox').each(function () {
    
            // Start by removing any previous error
            removeCheckboxError(this);
    
            // Add a new error if the checkbox is unchecked
            if (!$(this).is(':checked')) {
                $(this).parent().after('<span class="error">This field is required...</span>');
                valid = false;
            }
        });
        
        // Only allow the form to submit if all checkboxes were valid
        return valid;
    });
    
    // Remove error from a checkbox when clicked
    $('form.checkout input:checkbox').click(function () {
        removeCheckboxError(this);
    });
    
    // Reusable function to remove errors
    function removeCheckboxError(checkbox) {
        $(checkbox).parent().next('.error').remove();
    }
    

    JSFiddle here

    Login or Signup to reply.
  2. 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.

    var numOfReqCheckbox = 1; // number of checkboxes required
    var errorHtml = "<span class='error'>This field requerd....</span>";
    $('#submit').on('click', function () {
      var numOfCheckedCheckbox = $('input:checkbox:checked').length;
    if (numOfCheckedCheckbox < numOfReqCheckbox) {
        $("#checkout_terms").append(errorHtml);
    } else {
        $("#checkout_terms .error").remove();
        $('form.checkout').submit();//submit form
    }
    });
    .error {color: red;}
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <form class="checkout">
    <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>
       <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>
       <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>
    <input type="button" value=" Submit " id="submit">
    </form>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search