Luis Luis - 2 months ago 13
jQuery Question

Jquery Foreach inside Foreach

I'm trying to do a foreach inside another foreach.
The first one is to foreach every WodTabIndex class found and the seconds one every input, link and select found.

here's my code

var StartId= 500; $('.WodTabIndex').each(function(){
var $this = $(this);
$this.children(':input:visible, input[type="checkbox"], a, select').each(function(i){
(this).attr('tabindex', StartId + i);
(this).attr('tabindex', StartId + i);
});
});


I'm doing something wrong, but i don't know what. because never enters in the seconds foreach.

Sample fiddle: https://jsfiddle.net/lfvo/wk3w237y/

Answer

There are two issues with the code as posted:

First, you need to use .find rather than .children. Children only look at the direct descedants, not at the entire DOM below the item.

So for this html:

<div id='top'>
    <ul>
      <li></li>
      <li></li>

Code with $("#top").children("li") will not find the lis.

The second is that you need to use $(this) inside the loop otherwise you get this.attr is not a function


Updated code from the question:

var startId = 500; 
$('.WodTabIndex').each(function(){
    var $this = $(this);
    $this.find('input:visible, input[type="checkbox"], a, select').each(function(i){
        $(this).attr('tabindex', startId + i);
    });
});
Comments