Categories
JavaScript Answers

How to change background color of text box input when empty with JavaScript?

Spread the love

Sometimes, we want to change background color of text box input when empty with JavaScript.

In this article, we’ll look at how to change background color of text box input when empty with JavaScript.

How to change background color of text box input when empty with JavaScript?

To change background color of text box input when empty with JavaScript, we can check the input value and set the background.

For instance, we write:

<input type="text">

to add the input.

The we write:

const checkFilled = (input) => {
  if (!input.value) {
    input.style.backgroundColor = 'red'
  } else {
    input.style.backgroundColor = null
  }
}

const input = document.querySelector('input')
input.onchange = (e) => {
  checkFilled(e.target)
}
checkFilled(input)

to create the checkFilled function that takes the input element.

In it, we check if the input value if empty with !input.value.

If it is, we set the background color to red with input.style.backgroundColor = 'red'.

Otherwise, we set the backgroundColor to null to remove the background color.

Next, we select the input with querySelector.

Then we set input.onchange to a function that calls checkFilled with the input, which is the value of e.target.

And we also call checkFilled at the end to run it when the page loads.

Conclusion

To change background color of text box input when empty with JavaScript, we can check the input value and set the background.

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 *