Myy
Myy

Reputation: 18527

how to use the variable in a for loop in Javascript?

I have a dataTable which I need to iterate through. so I have this code:

var tableSize = $('#j_idt11\\:dataTable tbody tr').length;
for(i = 0;i< tableSize;i++){
    var test1 = document.getElementById("j_idt11:dataTable:0:updFoodType").textContent;
    if(test1 == "food")
        alert("hey");
}

but I really want to use the i in the for loop. I thought something like this:

var tableSize = $('#j_idt11\\:dataTable tbody tr').length;
for(i = 0;i< tableSize;i++){
    var test1 = document.getElementById("j_idt11:dataTable:[i]:updFoodType").textContent;
     if(test1 == "food")
         alert("hey");
}

but that doesn't work. how must I use the syntax? Thanks!

Upvotes: 0

Views: 107

Answers (2)

Hunter McMillen
Hunter McMillen

Reputation: 61540

You just need to concatenate the value of i with your string:

var tableSize = $('#j_idt11\\:dataTable tbody tr').length;
for(i = 0;i< tableSize;i++)
{
   var test1 = document.getElementById("j_idt11:dataTable:" + i + ":updFoodType").textContent;
   if(test1 == "food")
      alert("hey");
}

Upvotes: 1

Andrew
Andrew

Reputation: 13863

The for loop has nothing to do with it, you need to concatenate the string,

for(var i = 0;i< tableSize;i++){
  var test1 = document.getElementById("j_idt11:dataTable:" + i + ":updFoodType").textContent;
  if(test1 == "food")
     alert("hey");
}

Also be careful with globals, you should declare i in the local scope as well.

Upvotes: 1

Related Questions