Luis Luis - 1 year ago 214
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:

Answer Source

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'>

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; 
    var $this = $(this);
    $this.find('input:visible, input[type="checkbox"], a, select').each(function(i){
        $(this).attr('tabindex', startId + i);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download