Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter function for both empty and number fields

Tags:

jquery

I have a function that I am using to make sure that there is a value in at least one of three input fields by getting the count of all fields not empty, and passing based on that count != 0.

However, I am trying to modify this function to also fail if any of the inputs have something other than a number. I am unsure how to get this working 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>
like image 543
user2168066 Avatar asked Feb 28 '26 19:02

user2168066


1 Answers

To make this work, use Number() to convert the value in the filter(). This works because a 0 will coerce to false in the return value from filter(), and an empty value or a non-numeric value will return NaN which also coerces to false. Also note that you should check the length property against an integer value, not a string. Try this:

$('#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>
like image 137
Rory McCrossan Avatar answered Mar 03 '26 10:03

Rory McCrossan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!