I am trying to iterate through elements to add sequential numbering to them.
Example: I have 6 input elements, I want to count how many inputs there are and then change their name to match their number “name=input1”, “name=input2”, and so on. I’m using a for loop to reset this each time an element is added or removed.
Here is the function I’ve been trying (and failing) to implement:
JavaScript
x
11
11
1
function count(){
2
console.log(numChildren)
3
var childCount = document.getElementById("items").childElementCount;
4
console.log(childCount + " = number of children")
5
numChildren = [];
6
for (var i = 0; i < childCount; i++) {
7
numChildren.push(i+1)
8
document.querySelector("input[name*='item_name_']").name = "item_name_" + numChildren[i];
9
}
10
};
11
Advertisement
Answer
Something like this would work:
JavaScript
1
7
1
const nodes = document.getElementById("items").children;
2
3
for (var i = 0; i < nodes.length; i++) {
4
5
nodes[i].setAttribute('name', 'item_name_'+(i+1));
6
7
}
JavaScript
1
11
11
1
<html>
2
3
<body>
4
<div id="items">
5
<input type="text" name="item" />
6
<input type="text" name="item" />
7
<input type="text" name="item" />
8
<input type="text" name="item" />
9
</div>
10
</body>
11
</html>