Cltcoder
Cltcoder

Reputation: 1

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);
});

Upvotes: 0

Views: 841

Answers (2)

Eric Guan
Eric Guan

Reputation: 15990

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.

Upvotes: 1

Cory
Cory

Reputation: 1283

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/

Upvotes: 0

Related Questions