Categories
JavaScript Answers

How to check if any text input has value with JavaScript?

Spread the love

Sometimes, we want to check if any text input has value with JavaScript.

In this article, we’ll look at how to check if any text input has value with JavaScript.

How to check if any text input has value with JavaScript?

To check if any text input has value with JavaScript, we can use document.querySelectorAll to select all the inputs.

Then we can spread the node list into an array and use the array some method to check whether any element has a value set.

For instance, we write:

<input>
<input value='foo'>
<input>

to add some inputs.

Then we write:

const hasValue = [...document.querySelectorAll('input')]
  .some(el => el.value)
console.log(hasValue)

to select all the inputs with document.querySelectorAll.

Then we spread the node list into an array with the spread operator.

Then we call some to check whether any input has value set.

Therefore, hasValue should be true.

Conclusion

To check if any text input has value with JavaScript, we can use document.querySelectorAll to select all the inputs.

Then we can spread the node list into an array and use the array some method to check whether any element has a value set.

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 *