Reputation: 5
I'd like to know how to dynamically generate an ID on every input tag based off of it's name. I have to do this using javascript only - Not jQuery.
So, for example, if I have the following text inputs:
<input type="text" name="input1" value="">
<input type="text" name="input2" value="">
<input type="text" name="input3" value="">
I'd like to end up with this:
<input id="input1" type="text" name="input1" value="">
<input id="input2" type="text" name="input2" value="">
<input id="input3" type="text" name="input3" value="">
Any help would be appreciated, Thanks!
Upvotes: 0
Views: 200
Reputation: 55750
In plain JS, you can get the elements basis of tag name. And then set the id attribute for that element
function setinputIds() {
var inputs = document.getElementsByTagName('input');
for(var i=0;i < inputs.length; i++) {
var id = inputs[i].getAttribute('name');
inputs[i].setAttribute("id", id);
}
}
Upvotes: 1
Reputation: 262
Probably you can use a for loop to iterate name and insert id like this:
for(i=1;i<4;i++){
document.getElementsByName('input'+i).id='input'+i;
}
Upvotes: 0
Reputation: 12089
var inputs = document.getElementsByTagName('input');
for (var ii=0, item; item = inputs[ii]; ii++) {
item.id = item.name;
}
Upvotes: 0