简体   繁体   中英

how to make a form not submit if the checkbox is not selected

I have form in a ecommerce solution. I dont have access to the code other than that i can add a footer and header. So i can write some js and css codes.

I want to add a checkbox which i can by using

  <input type="checkbox"  name="checkbox1" class="default-input sale-text-req"/>Please read the <a href="#">Terms and Conditions</a>

I want to make sure that form is not submitted until the checkbox is selected. I do have the name/id of the order button. Any idea how this can be achieved

Thanks

Prady

Bind validation to your form's submit event like so:

$("form").submit(function (e) {
    if(!$("input[name='checkbox1']").is(":checked")) {
        e.preventDefault();
    }
});

Another option would be to prevent the submit button from being enabled until the user has selected the terms and conditions. You could also bake more validation in, in this form:

 function checkTerms() {
     if(document.formname.checkboxname.checked)
     {
         document.formname.submitname.disabled=false;
     }
     else
     {
         document.formname.submitname.disabled=true;
     }
 }

OR with JQuery:

 function checkTerms() {
     if($('input[name="checkbox1"]').is(":checked")
     {
         $('input[name="submitname"]').attr('disabled', 'disabled');
     }
     else
     {
         $('input[name="submitname"]').removeAttr('disabled');
     }
 }

Finally on your checkbox you would fire the validation when the click occurs:

 <input type="checkbox"  name="checkbox1" class="default-input sale-text-req" onclick="checkTerms();"/>

In the onsubmit attribute, check for the value of the element. If it's unchecked, use return false .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM