Categories
JavaScript Answers

How to check if an input value is empty and display an alert with JavaScript?

Spread the love

Sometimes, we want to check if an input value is empty and display an alert with JavaScript.

In this article, we’ll look at how to check if an input value is empty and display an alert with JavaScript.

How to check if an input value is empty and display an alert with JavaScript?

To check if an input value is empty and display an alert with JavaScript, we can check the value property of the input to see if it’s blank.

For instance, we write:

<form>
  <input>
  <button type='submit'>submit</button>
</form>

to add a form.

Then we write:

const form = document.querySelector('form')
const input = document.querySelector('input')

form.onsubmit = (e) => {
  e.preventDefault()
  if (!input.value) {
    alert('Input can not be left blank');
  }
}

to select the form and the input with querySelector.

Then we set the form.onsubmit to a function that checks if the input value is blank with !input.value.

If it’s true, then we display the alert.

Conclusion

To check if an input value is empty and display an alert with JavaScript, we can check the value property of the input to see if it’s blank.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *