Homer_J
Homer_J

Reputation: 3323

jQuery Creating Function in a loop

I have the following code:

    $('.edu2').click(function() {
        $('.edusub2').toggle().delay( 2000 );
    });
    $('.edu3').click(function() {
        $('.edusub3').toggle().delay( 2000 );
    });
    $('.edu4').click(function() {
        $('.edusub4').toggle().delay( 2000 );
    });
    $('.edu5').click(function() {
        $('.edusub5').toggle().delay( 2000 );
    });
    $('.edu6').click(function() {
        $('.edusub6').toggle().delay( 2000 );
    });

Instead of having six different functions, is it possible to create them in a single function, i.e. a loop:

I have tried the following:

    for (i = 2; i <= 6; i++) {
        $('.edu'+i).click(function() {
            $('.edusub'+i).toggle().delay( 2000 );
        });
    }

HTML

<tr class='td1 noborder pointer education'><td  style='padding-left:10px'><b> + </b>ISCS</td>
<td style='text-align:center;'>0</td><tr class='td1 noborder pointer edu2'>
<td  style='padding-left:20px;background-color:#CCC;'><b> + </b>Cis</td>
<td style='text-align:center;background-color:#CCC;'>0</td>
<tr class='td1 noborder edusub2'>
<td  style='padding-left:30px;background-color:#DDD;'><b> - </b>DM 5</td>
<td style='text-align:center;background-color:#DDD;'>0</td>
<tr class='td1 noborder pointer edu3'>
<td  style='padding-left:20px;background-color:#CCC;'><b> + </b>CRF</td>
<td style='text-align:center;background-color:#CCC;'>0</td>
<tr class='td1 noborder edusub3'>

etc.

But no joy. Any suggestions welcomed.

Upvotes: 0

Views: 29

Answers (2)

PeterKA
PeterKA

Reputation: 24638

You can easily achieve this with a little planning by (1) giving the elements a common class, say edu and (2) adding a data-attribute, say data-target, to each element that will hold the target element. Then you code would look something like:

$('.edu').click(function() {
    var target = $(this).data('target');
    $(target).toggle().delay( 2000 );
}); 

Sample html

.... class="edu1 edu" data-target=".edusub1" ....

Upvotes: 1

Richard Hamilton
Richard Hamilton

Reputation: 26434

It turns out that using a for loop is not the optimal solution here. This is because the value of the index variable gets incremented. It's better to use jQuery's each function. Here is an example.

$("button").each(function() {
    $(this).on("click", function() {
        $(".edusub" + ($(this).index() + 2)).toggle();
    });
});

http://jsfiddle.net/by6pu11k/1/

Disclaimer: I do not know what your code looks like but I do know you mentioned table rows. I tried to create this example based on the information you gave us. For this example, I created 5 buttons with the .edu class and 5 table rows.

Upvotes: 2

Related Questions