For Loop Not Incrementing

Hello

I am jsut struggling with a problem, so IU was hoping someone would be able to offer some assistance.

I have the following For loop:

$('table').each(function() {
    $this = $(this);
    var row_count = $this.find('tr').length;
    row_count -= 2;
    for (var i=1; i <= row_count; i++) {
        if ($this.find('td.rank').parent().prop('rowIndex') === i) {
	    $this.find('td.rank').html(i);
	}
    }
});

Instead of setting each rank td to 1, 2, 3, 4, 5 as I am expecting, it is instead setting it to 1, 1, 1, 1, 1. I am sure the reason is right in front of me, but I cannot seem to figure it out.

Could someone offer some advice as to where I could be going wrong?

Thank you so much!

$this refers to the table… Think about what this line actually does…

Hint: If I said $(‘table’).html(“meatball”), which table does it modify? How do i fix that?

$('table').each(function() {
    $this = $(this);
    var row_count = $this.find('tr').length;
    row_count -= 2;
    for (var i=1; i <= row_count; i++) {
        $this.find('td.rank').each(function() {
            if($(this).parent().prop('rowIndex') === i) {
	        $(this).html(i);
	    }
        })
    }
});

This is what I would need to do !

So. Lets look at your lines:

    if ($this.find('td.rank').parent().prop('rowIndex') === i) {
    $this.find('td.rank').html(i);
}

Now, lesson number 1: You’re correct about making changes; if you make a change to a group, you affect ALL members of that group.
Lesson number 2: If you request a VALUE from a group, you get the value of the first element. That’s how you are able to do === i without it having a conniption fit.

$this.find('td.rank').parent().prop('rowIndex') will always return the value of the first row’s rowIndex. So 1.

1 === i is a simple comparison.

$this.find('td.rank').html(i);

So now turn ALL the td.rank’s in this table into "1"s.

Loop starts again.
$this.find(‘td.rank’).parent().prop(‘rowIndex’) is still 1.
i is 2.
not true.

loop starts again.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.