user1575921
user1575921

Reputation: 1088

select item in for loop

in this for loop why not loop all the input ?

I tried in jquery each it work.. but I want use for loop do I miss something

I want to add class to all input not has class .typeLimit , and select item in the loop

https://jsfiddle.net/6v8arLqa/

var type = 'number';

for (var i = 0; i < $('input[data-type-limit="' + type + '"]').not('.typeLimit').length; i++) {
    console.log(i)
    var input = $('input[data-type-limit="' + type + '"]').not('.typeLimit').eq(i);
    console.log(input)
    input.addClass('typeLimit');
 }


<input type="text" data-type-limit="number" placeholder=":1">
<input type="text" data-type-limit="number" placeholder=":2">
<input type="text" data-type-limit="number" placeholder=":3">
<input type="text" data-type-limit="number" placeholder=":4">
<input type="text" data-type-limit="number" placeholder=":5">
<input type="text" data-type-limit="number" placeholder=":6">
<input type="text" data-type-limit="number" placeholder=":7">
<input type="text" data-type-limit="number" placeholder=":8">
<input type="text" data-type-limit="number" placeholder=":9">
<input type="text" data-type-limit="number" placeholder=":10">

test with each

$.each($('input[data-type-limit="' + type + '"]').not('.typeLimit'), function(i, val) {
console.log(i)
      var input = $(this);
      input.addClass('typeLimit');
  });

Upvotes: 0

Views: 162

Answers (1)

Mike Cluck
Mike Cluck

Reputation: 32511

Because every time you go through the loop, the contents of $('input[data-type-limit="' + type + '"]').not('.typeLimit') are changing so you're going to skip some elements. To prevent this problem (and be much more efficient) you can cache the results and work through those.

var $noTypeLimit = $('input[data-type-limit="' + type + '"]').not('.typeLimit');
for (var i = 0; i < $noTypeLimit.length; i++) {
  var $input = $noTypeLimit.eq(i);
  $input.addClass('typeLimit');
}

Or if all you're doing is adding a class to them, you can simplify it even more.

$('input[data-type-limit="' + type + '"]')
  .not('.typeLimit')
  .addClass('typeLimit');

Upvotes: 1

Related Questions