简体   繁体   中英

Using jQuery toggle to hide/show form submit button based on checkbox being checked - how to set submit button toggled off by default?

I have a form that I'm using whereby I would like to require a checkbox ('terms') to be checked in order to toggle the Submit button ('checkout-submit') on. I have it working just fine once you check the checkbox and then uncheck, etc.

But, by default the Submit button is showing. I'm unsure in my code how to ensure that the Submit button is toggled off when the page loads.

$('#terms').click(function() {
$("#checkout-submit").toggle(this.checked);
});

Another approach is to put the boolean attribute required on the checkbox, like so

<input type="checkbox" required>

Then if the user attempts to submit without checking the box, a native html5 dialog (which looks quite nice) appears, saying you have to check the box to proceed. The user can hit submit as many times as they like, but nothing will happen until the checkbox is checked. Note that all of this has to be inside a form element.

You can do something like this:

  $('#your_checkbox').click(function() {
    if ($(this).is(':checked')) {
      $('#your_button').removeAttr('disabled');

    } else {
        $('#your_button').attr('disabled', 'disabled');
    }
});
//set it to disabled at load 
$('#your_button').attr('disabled', 'disabled');

Fiddle http://jsfiddle.net/t70cc43o/1/

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