Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
99
rated 0 times [  103] [ 4]  / answers: 1 / hits: 12235  / 10 Years ago, fri, april 11, 2014, 12:00:00

I am trying to create a dynamic js table and I want to give id to each cell dynamically. I want to use those ids to use in different js event handlers. How it can be done? I have tried in different ways but none of them works!



<html>

<head>
<style>
#colors {
float: right;
width: 400px;
height: 400px;
}
</style>
</head>

<body>
<script>
var d;
var k = 0;
function makeit() {
var tbl = document.createElement(table);
var atts = document.createAttribute(style);
atts.value = border:1px solid black;text-align:center;padding:2px;margin:3px 3px 3px 3px;;
tbl.setAttributeNode(atts);
for (i = 0; i < 5; i++) {
var rows = tbl.insertRow(i);

for (j = 0; j < 7; j++) {
d = rows.insertCell(j);
d.height = 50px;
d.width = 50px;
d.style.backgroundColor = yellow;
d.addEventListener(click, function myfunc() { d.style.backgroundColor = red; });


}
}


document.body.appendChild(tbl);
}

window.onload = makeit;
</script>
</body>

</html>

More From » dynamic

 Answers
4

Just add



d.id = r + i + c + j;


under



d=rows.insertCell(j);


to set unique ids on each td.

Obviously, you can change the syntax r2c4 (which would be 3. row and the 5. cell) to your own liking.



If you want to call a function when clicking on a specific td you could even pass the row index (i) and column index (j) to that function.



Side note

You should consider using a JavaScript library or framework like jQuery for manipulations like this. It would facilitate your work a lot in the long term.


[#46115] Thursday, April 10, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kylie

Total Points: 121
Total Questions: 84
Total Answers: 91

Location: Jordan
Member since Thu, Aug 5, 2021
3 Years ago
;