Alator. Alator. - 6 months ago 9
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

id
of the elements inside the rows dynamically. I have set a global variable
i
which I set as an id to some elements inside my table. The problem is that after some debugging I found out that the
id
doesn't change at all and stays as the letter i (and not the variable
i
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>
</tr>");

$("#a2").click(function(){
$z=$("#a1").val();
$("#a3").attr("src",$z);
i++;
});

Answer

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 +.

$("#table1").append(
  "<tr>" +
    "<td>" + 
      "<center><input id=\"" + a1 + "\" /></center>" +
    "</td>" +
    "<td>" +
      "<center><input id=\"" + a2 + "\" /></center>" +
    "</td>" +
    "<td>" +
      "<center><input id=\"" + a3 + "\" /></center>" +
    "</td>" +
  "</tr>"
);

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.