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.