Filter function for both empty and numeric fields
I have a function that I am using to make sure there is a value in at least one of the three input fields by getting the count of all non-empty fields and passing based on that number! = 0.
However, I am trying to modify this function so that it also fails if any of the inputs have anything other than a number. I'm not sure how to do this using my current structure.
$('#go').on('click', function() {
var nonempty = $('.number').filter(function() {
return (this.value) != 0;
// return isNaN(this.value);
})
if (nonempty.length == '') {
alert('Fail');
} else {
alert('Pass');
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class='number'>
<input class='number'>
<input class='number'><br/>
<button id='go'>Go!</button>
source to share
To make this work, use Number()
to convert the value to filter()
. This works because it 0
will coerce false in the return value from filter()
, and an empty or non-numeric value will return NaN
, which will also be forced to false. Also note that you must check the property length
for an integer value, not a string. Try the following:
$('#go').on('click', function() {
var nonempty = $('.number').filter(function() {
return Number(this.value);
})
if (nonempty.length == 0) {
console.log('Fail');
} else {
console.log('Pass');
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="number">
<input class="number">
<input class="number"><br/>
<button id="go">Go!</button>
source to share