Search code examples
javascripthtmlclone

Trying to clone a form and increment the id of the clones


function moreFields() {
     counter++;
     var newFields = document.getElementById("input").cloneNode(true);
     newFields.id = counter;
     newFields.style.display = 'block';
     var newField = newFields.childNodes;
     for (var i=0;i<newField.length;i++) {
         var theName = newField[i].id;
         if (theName) {
             newField[i].id = theName + counter;
            }
        }
     var insertHere = document.getElementById("buttons");
     insertHere.parentNode.insertBefore(newFields,insertHere);
}

function clear() {
     var count = counter;
     while (count>0) {
         var pricetxt = document.getElementById('price'+count);
         pricetxt.value = "";
         var qtytxt = document.getElementById('qty'+count);
         qtytxt.value = "";
         count--;
        }
}

here is the jsfiddle for the page

http://jsfiddle.net/xjsc16x/TctQx/1/

Sorry, I know it's big but I can't figure out what is wrong. The moreFields function copies the fields correctly (just 2 textboxes) but I'm not sure that it is implementing the incrementing id corectly.

I think that I have the clear function correct but it can't read the ids? Can anyone help me please?


Solution

  • Change name of clear() and it works. You've run into a javascript reserved word, clear is a window method

    DEMO: http://jsfiddle.net/TctQx/3/