HTML Interface

Example

In this example, an <input> element's input event is monitored in order to update the state of a form's "submit" button based on whether or not a given field currently has a value.

JavaScript

const nameField = document.getElementById("userName");
const sendButton = document.getElementById("sendButton");

sendButton.disabled = true;
// [note: this is disabled since it causes this article to always load with this example focused and scrolled into view]
//nameField.focus();

nameField.addEventListener("input", (event) => {
  const elem = event.target;
  const valid = elem.value.length !== 0;

  if (valid && sendButton.disabled) {
    sendButton.disabled = false;
  } else if (!valid && !sendButton.disabled) {
    sendButton.disabled = true;
  }
});


This code uses the Document interface's getElementById() method to get the DOM object representing the <input> elements whose IDs are userName and sendButton. With these, we can access the properties and methods that provide information about and grant control over these elements.

The HTMLInputElement object for the "Send" button's disabled property is set to true, which disables the "Send" button so it can't be clicked. In addition, the user name input field is made the active focus by calling the focus() method it inherits from HTMLElement.

Then addEventListener() is called to add a handler for the input event to the user name input. This code looks at the length of the current value of the input; if it's zero, then the "Send" button is disabled if it's not already disabled. Otherwise, the code ensures that the button is enabled.

With this in place, the "Send" button is always enabled whenever the user name input field has a value, and disabled when it's empty.


HTML

The HTML for the form looks like this:

<p>Please provide the information below. Items marked with "*" are required.</p>
<form action="" method="get">
  <p>
    <label for="userName" required>Your name:</label>
    <input type="text" id="userName" /> (*)
  </p>
  <p>
    <label for="email">Email:</label>
    <input type="email" id="userEmail" />
  </p>
  <input type="submit" value="Send" id="sendButton" />
</form>