unrealindeed unrealindeed - 19 days ago 8
Javascript Question

Include checkbox validator on page with two forms

I have a payment page. At the top of the page I have a standard div with some "Please confrim you agree to the T's & C's" text and a checkbox.

Underneath that there are two separate forms each with a different payment option/button "Pay by cheque" and "pay by card".

Is it possible to validate a checkbox on both form submit buttons as the user can pick the payment option?

Note: The div is outside of both forms. I don't think nested forms are strictly legal.

I'm also using Foundation 6 Framework, considering using the abide, but I'm stuck as to how to validate if the checkbox is checked for both submit buttons.

Any help appreciated.

forms

Answer

Override default's form submit, check if the checkbox is checked and then submit the form.

Example code:

$(function(){
  $("#form1, #form2").on('submit', function(){
    if($("#terms:checked").length) {
      $(this).submit(); //if checked, submit form
    }
    else {
      alert('Please accept the terms'); //else show form errors
    }
    return false;
  });
});

If you use jQuery validation plugin you can use $("#terms").valid() instead of $("#terms:checked").length.

Here is a simple example I created for you: fiddle

Comments