TTT
TTT

Reputation: 4434

jquery class selector inside a loop

I have a simple question about the expression in jquery to select a class which involved a for loop. Basically, I have two steps: 1. Generate some html tables with a loop. 2. Use jQuery to unhide them.

Below is the simplified code to 1. generate html tables (I will add a loop index to separate each loop created tables) : 2. the key part of the second step is to unhide generated tables. My selector is written as: method_options_1'+i+', where i is a for loop index.

for (var i = 2; i <= 5; i++) {
  <tr class="method_options_1'+i+'" style="display: none;"><th><label for="id_CAM_1">Chemical application Method (CAM):</label></th>
      <td><select name="CAM_1_'+i+'" id="id_1_'+i+'">
        <option value="2">2-Interception based on crop canopy</option>
        <option value="9">9-Linear foliar based on crop canop</option></select>
      </td></tr>

  $('.method_options_1'+i).closest('tr').show();  
}

However, this selector does not work, which means I could not show the hidden element. While, if I remove the index i from both the HTML and jquery, the selector works. Since I have to keep the i index, can anyone give me some suggestions (I tried to remove closest('tr'), but it does not work)?

Upvotes: 0

Views: 532

Answers (3)

KoU_warch
KoU_warch

Reputation: 2150

I really wonder how you run the above code... however doing this does work

HTML:

 ​<table id='myTable'>
 </table>​​​​​​​​

JavaScript:

$(function(){

  for (var i = 2; i <= 5; i++) {
     $('#myTable').append('<tr class="method_options_1'+i+'" style="display: none;"><th><label for="id_CAM_1">Chemical application Method (CAM):</label></th><td><select name="CAM_1_'+i+'" id="id_1_'+i+'">        <option value="2">2-Interception based on crop canopy</option>        <option value="9">9-Linear foliar based on crop canop</option></select>      </td></tr>');


     $('.method_options_1'+i).closest('tr').toggle('slow');   
  }


})

Solution

Upvotes: 0

flagoworld
flagoworld

Reputation: 3194

That's because as far as Javascript is concerned, name is simply a string: method_options_1'+i'. It does not evaluate any code inside that string. If you want to do it correctly, do something like this:

HTML:

<tr class="method_options">etc</tr>

Javascript:

$('.method_options:eq('+i+')').show();

EDIT:

Perhaps I misunderstood. You are generating this inside a Javascript for loop, so i is a valid variable in code space. If that's the case, then you simply have to take out closest(), as it tells jQuery to travel up the DOM and select the first tr that it finds. In this case, that appears to be nothing. You want to work on the tr that you selected, not a tr that is a parent of the one you are selecting.

Upvotes: 0

biziclop
biziclop

Reputation: 14596

'.method_options_1'+i is already a tr, so first try removing the closest('tr') step:

$('.method_options_1'+i).show();

See http://jsfiddle.net/WJDCm/

Upvotes: 1

Related Questions