Marco Prins
Marco Prins

Reputation: 7419

jQuery each() and if statement only working for first element

I have this simple piece of jQuery code

$(document).ready( function () {
  $('#line_items_table tr').each( function () {
    var self = $(this);
    console.log(parseInt(self.attr('data-id')));
    if ( !$.inArray( parseInt(self.attr('data-id')), errors )) {
      console.log("inside conditional");
      self.addClass('incorrect_item');
    }
  });
});

With errors = [19,20,21], i get this output

3417
3419
"inside conditional"
3420
3421
3422 
3423 
3424 
3425

And errors = [20,21], this output:

3417
3419
3420
"inside conditional"
3421
3422
3423
3424
3425

Why is this only working for the first element??

Upvotes: 2

Views: 138

Answers (1)

adeneo
adeneo

Reputation: 318362

When using $.inArray, always check for -1, not just true or false

if ( $.inArray( parseInt(self.data('id'), 10), errors ) == -1 ) {

The reason is that $.inArray return the index of the found value, and for the first item that index is 0, which is falsy, and that's the reason it only works on the first one.

Upvotes: 8

Related Questions