Alfred
Alfred

Reputation: 21406

JavaScript multiple incrementing variable solution

I have a variable ver i = 1.

I have a table as follows;

<table>
<tr class="testrow">
<td class="prev">&nbsp;</td>
<td class="data">&nbsp;</td>
<td class="next">&nbsp;</td>
</tr>
<tr class="testrow">
<td class="prev">&nbsp;</td>
<td class="data">&nbsp;</td>
<td class="next">&nbsp;</td>
</tr>
<tr class="testrow">
<td class="prev">&nbsp;</td>
<td class="data">&nbsp;</td>
<td class="next">&nbsp;</td>
</tr>
<tr class="testrow">
<td class="prev">&nbsp;</td>
<td class="data">&nbsp;</td>
<td class="next">&nbsp;</td>
</tr class="testrow">
<tr>
<td class="prev">&nbsp;</td>
<td class="data">&nbsp;</td>
<td class="next">&nbsp;</td>
</tr>
</table>

The table may have more rows. I want a variable to increase value by 1 when I click next and decrease by 1 for prev. This can be done easily. But I want some variable which is row dependent. When I clicknext in first row, the variable value should be 2, but it should not change when I click either next or prev in any other row. Also this should be the case in all other rows. The minimum value of variable should be 1.

It will be helpful if someone provide me a fiddle with the variable displayed in the middle cell of each row. Note that in this demo, it should not be something to ++ or -- the text or data in the middle cell.

Here is my fiddle.

Upvotes: 0

Views: 294

Answers (3)

tskuzzy
tskuzzy

Reputation: 36476

Couldn't you keep an array of these counters (this would work if the number of rows is known beforehand and static)? Otherwise you could attach the counter to each <tr> element using the jquery data() function.

See: http://api.jquery.com/jQuery.data/

Upvotes: 0

Bj&#246;rn
Bj&#246;rn

Reputation: 2648

I'd use jQuery.data() to store the variable in each row, changing it when the user clicks prev/next:

$(function() {

    $(".testrow").each(function() {
        var $row = $(this);
        // set the initial value  
        $row.data("currentIndex", 1);

        $row.find(".prev").click(function() {
            $row.data("currentIndex", $row.data("currentIndex") - 1);
            alert("currentIndex: "+$row.data("currentIndex"));
        });
        $row.find(".next").click(function() {
            $row.data("currentIndex", $row.data("currentIndex") + 1);
            alert("currentIndex: "+$row.data("currentIndex"));
        });

    });

});

jsFiddle: http://jsfiddle.net/5TPCK/12/

Upvotes: 1

ThiefMaster
ThiefMaster

Reputation: 318698

$('table tr .next').click(function() {
    alert($(this).closest('tr').index());
});

http://jsfiddle.net/ThiefMaster/5TPCK/2/

Btw, </tr class="testrow"> is horribly wrong - it should only be </tr>.

Upvotes: 1

Related Questions