0

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!

3
  • 2
    It's easier for us to help you if your code is properly formatted. Commented Jul 25, 2012 at 18:31
  • possible duplicate of How do i put a variable in a string using javascript Commented Jul 25, 2012 at 18:33
  • 1
    If you could write a better selector you could just use $(..).each(fn) .. and if using jQuery (or another magical $ variant), it is sort of silly to mix in usages of document.getElementById as well. Commented Jul 25, 2012 at 18:37

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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");
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.