Alator. Alator. - 1 year ago 42
Javascript Question

How can i set an element's id as a variable?

I have some jQuery script in which I'm adding some rows to a table (when the user press a button). My problem is that I want to change the

of the elements inside the rows dynamically. I have set a global variable
which I set as an id to some elements inside my table. The problem is that after some debugging I found out that the
doesn't change at all and stays as the letter i (and not the variable
set to 0 and increase every time the user press the button). Any ideas?

var i=0;
var a1=i.toString().concat("1");
var a2=i.toString().concat("2");
var a3=i.toString().concat("3");
$("#table1").append("<tr><td><center><input id=\"a1\"></input></center></td><td>
center><button id=\"a2\">Load</button></center></td><td ><img id=\"a3\"></td>


Answer Source

That's because you're writing those directly as strings. You need to concatenate them into the actual string. You can concatenate strings together using +.

  "<tr>" +
    "<td>" + 
      "<center><input id=\"" + a1 + "\" /></center>" +
    "</td>" +
    "<td>" +
      "<center><input id=\"" + a2 + "\" /></center>" +
    "</td>" +
    "<td>" +
      "<center><input id=\"" + a3 + "\" /></center>" +
    "</td>" +

For what it's worth, the <center> tag is deprecated and should not be used. You may also consider creating some kind of template rather than generating your HTML as strings directly inside of JavaScript.