Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting dynamically distinct id attribute using javascript for input element

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.

like image 794
Chinmaya Kumar Panda Avatar asked Nov 12 '12 07:11

Chinmaya Kumar Panda


2 Answers

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

like image 56
gdoron is supporting Monica Avatar answered Nov 15 '22 01:11

gdoron is supporting Monica


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>
like image 30
Declan Cook Avatar answered Nov 15 '22 00:11

Declan Cook