How to Enable/Disable a Form Button with JavaScript

How to Enable or Disable a Form Button with JavaScript

In this snippet, we’re going to be exploring the addEventListener method together with the keyup event. And as for the example itself – we will create a simple input field and a button, and then use addEventListener together with a custom function to change the state of the button.

The state will change from disabled (default) to enabled whenever the user has put something inside the input field. As such, you can use this method to prevent users from submitting forms that haven’t been completely filled out. This is also often referred to as “required fields”.

Now, the use case for this is on a case-by-case basis. For example, if you write an email input field and append required to it, the user can click the button, but it won’t send the actual email until the form has been properly filled out. Read more about this on MDN.

Let’s look at some code, an example, and talk about what is happening.

CSSHTMLJavaScript
.form-style {
  display: flex;
  place-content: center;
  padding: 1rem;
  background-color: #f5f2f0;
}

.form-button {
  margin-left: 10px;
}
<div class="form-style">
<input class="form-input" type="text" placeholder="Enter some text">
<button class="form-button">Submit</button>
</div>
const formInput = document.querySelector(".form-input");
const formButton = document.querySelector(".form-button");

// the default state is 'disabled'
formButton.disabled = true; 

// alternative is to use "change" - explained below
formInput.addEventListener("keyup", buttonState);

function buttonState() {
    if (document.querySelector(".form-input").value === "") {
        formButton.disabled = true; // return disabled as true whenever the input field is empty
    } else {
        formButton.disabled = false; // enable the button once the input field has content
    }
}

// just verifying that the button has been clicked
formButton.addEventListener("click", () => {
console.log("You entered:", document.querySelector(".form-input").value);
});

And here is a demo form to showcase the final result:

The first thing to note here is that the button state changes immediately after you enter some text.

This is because for this demo we’re using the keyup event listener rather than change.

When using change – the user has to click outside the form or target the next input field for the state to change, which in some cases might be confusing for the user. Also, the nice thing about keyup event is that it will automatically disable the button again when the input field has been cleared.

You can also verify that the button works by checking your console.log as it should display the text you entered whenever you click it in its active (non-disabled) state.