0

In my program, I use javascript to generate a table which is then appended to the html document:

var html = "<table>";
for (var r = 0; r < rows; r++)
{
    html += "<tr>";
    for (var c = 0; c < cols; c++)
    {
        html += "<td class=\"covered\"><input type=\"image\" src=\"imageURL.com"/></td>";
    }
    html += "</tr>";
}

html += "</table>";
$(".gameboard").append(html);

I want each of the input elements to have a unique ID -- specifically a number. I was hoping to have a variable that is initialized to 1, which gets incremented each time a TD element is created. The value of this variable would be used as the input element ID. I haven't found any way to do this specifically. Thanks in advance!

1
  • Use UserId+indexId to usniquely define the id. Commented Jan 21, 2014 at 7:01

4 Answers 4

1

Try this:

var html = "<table>";
var index=0;

for (var r = 0; r < rows; r++)
{
html += "<tr>";

for (var c = 0; c < cols; c++)
{
    html += "<td class=\"covered\"><input id='img"+(index++)+"' type=\"image\" src=\"imageURL.com"/></td>";
}
html += "</tr>";
}

html += "</table>";
 $(".gameboard").append(html);
Sign up to request clarification or add additional context in comments.

1 Comment

This code will still not work... the syntax highlighting is a hint.
0

Try to add a global variable let count and increment it in inner loop, like,

var html = "<table>";
var count=1;// use this variable in inner for loop and increment it by 1
for (var r = 0; r < rows; r++)
{
    html += "<tr>";
    for (var c = 0; c < cols; c++){
        html += "<td class=\"covered\">\
                  <input id='"+(count++)+"' type=\"image\" src=\"imageURL.com\"/>\
                </td>";
    }
    html += "</tr>";
}

html += "</table>";
$(".gameboard").append(html);

Comments

0

Try this code:

html += "<td id='td-" + c +"'class=\"covered\"><input value='td-" + c +"' type=\"image\" src=\"imageURL.com"/></td>";

Comments

0

use this

 var ID= new Date().getTime(); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.