Disable a button until a checkbox is checked.

In this tutorial, I will show you how to disable a HTML button until a checkbox is checked. I will include both a JQuery and a regular “vanilla” JavaScript example.

This is most-commonly used on HTML forms that have some sort of Terms and Conditions checkbox that the user must tick before they can sign up.

The best way to approach this is to disable the HTML button by default. i.e. Set the button to disabled using the disabled HTML attribute and then enable it using JavaScript if the checkbox is ticked.

Disabling a button until a checkbox is checked using regular JavaScript.

Let’s start off with an example that does not use JQuery.

Below, I have created an extremely basic HTML form:

The HTML above contains a checkbox with the ID “terms_and_conditions” and a button called “submit_button”, which submits the form. There are two things to note here:

  1. We have added an inline event handler to the checkbox input. If a user clicks on the checkbox, a JavaScript function called terms_changed will be called. The this parameter that we are passing into our function represents the event will occur when the user checks or unchecks the checkbox.
  2. Our button has been set to disabled by default because we used the disabled HTML attribute.

Now, let’s look at the JavaScript function that will be called when the user clicks on the checkbox:

The JavaScript function above checks to see if the checkbox in question has been ticked.

If it has been checked, then it sets the disabled property on our submit button to FALSE. Essentially, this enables the button.

However, if the user unchecks the checkbox, then our function will disable the button by setting the disabled property back to TRUE.

Disabling a button until a checkbox is checked using JQuery.

Now, let’s take a look at an example that uses the JQuery library.

The HTML form below is a slightly-modified version of the form that we created above. However, in this example, the checkbox doesn’t an have an inline event handler:

This is because we can attach a click event handler onto our checkbox using JQuery:

The JQuery example above is pretty simple:

  1. We attached a click event handler onto the terms and conditions checkbox.
  2. When the checkbox is clicked, our event handler checks to see whether or not the element has been set to “:checked”.
  3. If it is checked, we enable the submit button by setting the disabled property to FALSE. We do this by using JQuery’s attr() method.
  4. If it is not checked, then we set the disabled property to TRUE.

Note that for server-side validation, you might want to check out the following guide: Using checkboxes with PHP.

Facebook Comments