Question : Javascript - how to add number to field name (dynamic field add script)

Hi,
The script below adds additional form fields to my HTML form on button click.

The form field currently has a name and id of 'item'.

How do add a number to the end and increase for each additional field?

Eg:
item1
item2
item3
item4

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
<script language="javascript">
fields = 0;
function addInput() {
if (fields != 20) {
document.getElementById('text').innerHTML += "<label for='item'>Item</label><input type='text' value=''  name='item' id='item' style='margin-top:5px: width:200px;'/> Qty:<input type='text' value=''  name='qty' id='qty' style='margin-top:5px; width:15px;' /><br />";
fields += 1;
} else {
document.getElementById('text').innerHTML += "<br />Only 20 items fields allowed. Please call for larger orders";
document.form.add.disabled=true;
}
}
</script>


Thanks for any help

Answer : Javascript - how to add number to field name (dynamic field add script)

http://www.rodsdot.com/javascript/Adding-Dynamic-Rows-To-A-Table-After-Page-Load.asp

Shows how to properly add elements to a loaded DOM (page).

var el = document.createElement('input'); is the key portion.

[object reference] would be a reference to the form.
1:
2:
3:
4:
5:
6:
iteration += 1;
var el = document.createElement('input');
el.type = 'text';
el.name = 'item' + iteration;
el.id = 'item' + iteration;
[object reference].appendChild(el);
Random Solutions  
 
programming4us programming4us