Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Feb 2011
    Thanked 0 Times in 0 Posts

    Change the value of an attribute in array

    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;
    HTML Form
    <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>
    Last edited by apprentice; 02-17-2011 at 09:26 PM.

  2. #2
    Join Date
    Apr 2009
    Thanked 426 Times in 424 Posts
    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 [CODE][/CODE] tags, so it's easier to read.

  3. #3
    New to the CF scene
    Join Date
    Feb 2011
    Thanked 0 Times in 0 Posts

    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.
    Last edited by apprentice; 02-17-2011 at 09:27 PM.


Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts