I am facing a problem in setting distinct ids for dynamically added input boxes in a table. The problem is:
I am inserting new rows when the user clicks on "Add new Row". Now I have to set distinct id for the input box. I have taken a static variable and increasing its value every time user clicks on add new row button. Then I am appending its value to id value lets say temp (i.e. ids will be temp1
, temp2
and so on). I have taken a variable xyz as
var xyz = "temp" + i
(where i is the counter)
and now I have to assign xyz
to the id using setattribute
.
But as values in setattribute
can only be literals, how can I use a variable in place of the value?
If you have any other methods, please let me know.
It can be a variable which holds a string as well.
var fooId = "foo";
for (var i = 0; i <= 2; i++) {
document.getElementsByTagName('div')[i].setAttribute('id', fooId + (i + 1));
}
Live DEMO
setAttribute
allows for variables to be used as the value parameter.
eg:
var ele = document.createElement('div')
var id = 'temp1'
ele.setAttribute('id', id)
would result in:
<div id="temp1"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With