View Full Version : Change the value of an attribute in array

02-17-2011, 03:27 PM
I have a form with dynamic fields. Javascript is used to clone multiple fields. Each time a set of field is cloned, I am trying to set a unique name for each attribute .e.g yourname[], yourname_1[] yourname_2[]. The corresponding line is (newField[i].setAttribute("name", theName + "_" + i );) however its not seem to be working, values remain the same. What i'm I doing wrong?

var counter = 0;
function moreItems() {
var newFields = document.getElementById('readRoot').cloneNode(true);
newFields.id = '';
newFields.style.display = 'block';
var newField = newFields.childNodes;
for (var i=0;i<newField.length;i++) {
var theName = newField[i].name;
if (theName){
newField[i].name = theName + "_" + i;
newField[i].setAttribute("name", theName + "_" + i );

var insertHere = document.getElementById('writeroot');

//window.onload = moreItems;


<div id="readRoot">
<p>Your Name: <input id="text" name="yourname[]" />

<br />
E-mail: <input id="text" name="email[]"/>
<br />
Fav Colour: <input id="text" name="colour[]" /></p>

<span id="writeroot"></span>
<input type="button" value="Add Another Item" onclick="moreItems()" />

<p>Your comments:<br />
<textarea id="comments" name="comments" rows="10" cols="40"></textarea></p>

<p><input type="submit" value="Send it!"></p>


02-17-2011, 07:40 PM
The things you are looping over are not actually the inputs, but the child nodes of #readRoot, which are two empty text nodes and the <p>, which contains the inputs.

Also, even if you make this work, the way you have it set up the resulting names will be like "yourname[]_1", and not "yourname_1[]". And why do you need those brackets anyway if you're manually numbering the fields?

Oh, and please put your code in
tags, so it's easier to read.

02-17-2011, 08:19 PM

It doesnt actually matter if the output is yourname_1[] or yourname[]_1. I am trying to make the names unique. The brackets are not a big deal, they can be removed.

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum