Check if a HTML input element contains (no) user input

Last updated: May 10, 2022.

In form validation or creating an app, it is often useful to check if a HTML input element contains user input, so this can be handled appropriately.

For example, your HTML looks like the following:

<input type="text" id="input">
<button id="btn">Check input</button>

To check if a user has provided a value for the input element, you can check to see if the value of input is an empty string.

If you want to be as explicit as possible, you should use the strict equality operator:

/* Check for no user input by testing for an empty string */

document.getElementById('btn').addEventListener('click', () => { 
  if (document.getElementById("input").value !== "") {
    console.log("Input has a value!");
  } else {
    console.log("No input!");
  }
})

An alternative is to check if the value for the input element is falsy. This will be the case if the user has entered no value.

Note that, in the code below, document.getElementById("input").value is equivalent to writing document.getElementById("input").value == false.

/* Alternative: Check for a 'fasly' value */

document.getElementById('btn').addEventListener('click', () => { 
  if (document.getElementById("input").value) {
    console.log("Input has a value!");
  } else {
    console.log("No input!");
  }
})