In this article we will look at how to disable a button on a form until a checkbox is checked. This is an excellent way to make the user, subscriber accept a terms of service or privacy policy before subscribing on a newsletter or submitting some kind of information.

First let’s create a simple HTML page for our form. I link my own styles.css and script.js.

Copy code

Now let’s add the form:

Copy code

and add some styles to it in the style.css.

Copy code

The button will have two different styles depending on the state of the checkbox. By default the checkbox will be unchecked so we need to add a class of “.unchecked-btn” to the button and the styles.css and we also need to add a “.checked-btn” to the styles.css. These two classes will be toggled when the checkbox is turned on and off.

Copy to Clipboard

Now we are ready to create the necessary javascript to activate the button. To do this we need to create a small function in the script.js file.

Copy to Clipboard

So here we create a function called “activateButton”.

We also need to grab the submit button and the checkbox store them in variables called “submitButton” and “checkbox” respectively.

Then we just need an if statement to see if the box is checked or not.

We add the “checked” property to the “checkbox” variable and it will return the checked state of a checkbox. If it’s true (checked), it will add the “btn checked-btn” classes to the button (input) and it will also remove the “disabled” attribute from the HTML element.

If the condition is not true (not checked or unchecked), then we add the “btn unchecked-btn” classes and the “disabled” attribute.

After this the only thing we have to do is to add the “onchange” event to the button like this:

Copy to Clipboard

Get the full code from Codepen here.