Vince
Vince

Reputation: 3286

Dynamically assign unique id from var value in Javascript, jquery

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!

Upvotes: 0

Views: 810

Answers (4)

Rohan Kumar
Rohan Kumar

Reputation: 40639

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

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82231

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

Upvotes: 1

Dibu
Dibu

Reputation: 891

use this

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

Upvotes: 0

Felix
Felix

Reputation: 38102

Try this code:

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

Upvotes: 0

Related Questions