How to Enable and Disable Buttons with JavaScript (Based on State)

Learn how to disable or enable buttons based on whether or not an input field is empty.

When you fill out forms on the web you’ll notice that often you cannot submit the form until all or some text fields are filled (required fields). The same principle applies to checkboxes and radio buttons.

Here’s how to control the state of your button (enabled vs disabled) based on whether or not your input field is empty.

HTML

Add the following HTML to your editor:

<input class="input" type="text" placeholder="fill me" />
<button class="button">Click Me</button>

JavaScript

Add the following JavaScript

let input = document.querySelector(".input")
let button = document.querySelector(".button")

button.disabled = true

input.addEventListener("change", stateHandle)

function stateHandle() {
  if (document.querySelector(".input").value === "") {
    button.disabled = true
  } else {
    button.disabled = false
  }
}

Now you have a button that is disabled as long as your input field is empty, and enabled as soon as you start filling it.

Check out the demo with all the working code.

Demo code.

How the HTML & JavaScript code works

First, we define a couple of HTML elements, an input field, and a button. Then we use JavaScript to create two variables to store a reference to each element input & button. Now we have full control to manipulate each element programmatically.

We start by disabling the state of the button. By default, a button’s state is enabled in HTML. By using disabled = true the button is now grayed out (disabled) in the UI for the user.

Then we attach an event handler (addEventListener) to the input variable with the event property change, which is a property that listens (watches) for interactions with elements. In this case, we want to know when the user interacts with the input field by typing inside it, and then react to that event by running a function.

The function we run is called stateHandler and it fires every time there’s a change inside the input field.

The code inside the stateHandler says “if the value of the input field is an empty string (=== '') then disable the button, otherwise (else) enable it.


Has this been helpful to you?

You can support my work by sharing this article with others, or perhaps buy me a cup of coffee 😊

Kofi

Share & Discuss on