1

I have a set of text inputs fields which I want to be cloned when the user clicks the "add" button. My problem is that the fields are being cloned with the input from the user. Using Javascript, how do I reset the value of the text input fields so they may be cloned without cloning the user input text.

This is my code...

<table width="766"  border="0" cellspacing="0" cellpadding="0" id="albumTable">  
    <tr id="clone">  
        <td width="230"><input type="text" name="dj_1" /></td>  
        <td width="230"><input type="text" name="affiliations_1" /></td>  
        <td width="230"><input type="text" name="rating_1" /></td>  
        <td width="230"><input type="text" name="comments_1" /><input type="hidden" name="count" value="1" class="count"/></td>
        <td width="286" style="position:absolute; top:110px; left: 670px;"><input name="button" type="button" id="Add" value="ADD ROW" onclick="addRow(this.parentNode.parentNode)"></td>
    </tr>
</table>

<script type="text/javascript">
    function addRow(r){  
        var root = r.parentNode;  
        var allRows = root.getElementsByTagName('tr');  
        var cRow = allRows[0].cloneNode(true)  
        var cInp = cRow.getElementsByTagName('input');  
        var countRow = cRow.getElementsByClassName('count');  

        for(var i=0;i<cInp.length;i++){
            cInp[i].setAttribute('name',cInp[i].getAttribute('name').replace(/\d/g,(allRows.length+1)))   
        }  
        for(var j=0;j<countRow.length;j++){
            countRow[j].setAttribute('value',countRow[j].getAttribute('value').replace(/\d/g,(allRows.length+1)))
        }  
        root.appendChild(cRow);  
    }  

    function shownames(){
        var allInp=document.getElementsByTagName('input');
        for(var i=0;i<allInp.length;i++){
            alert(allInp[i].name)  
        }  
    }  
</script>
wattostudios
  • 8,666
  • 13
  • 43
  • 57
Pantone
  • 25
  • 1
  • 3

2 Answers2

0

Something like this:

var cln = document.getElementByID("clone");
var clns = cln.getElementsByTagName("td");

for(var i = 0; i <clns.length; i++)
{
   clns[i].innerHTML = "";
}
Kenneth Jakobsen
  • 458
  • 3
  • 11
  • If I add `cInp[i].value='';` the problem is that it resets the value of the submit button. Kenned's code helped me figure this out. The problem with using an empty value of innerHTML is that it wipes out all the input code. I did the following—adding the class "cloneInput" to each input field: `var cln = document.getElementById("clone"); var clns = cln.getElementsByClassName("cloneInput"); for(var i = 0; i – Pantone Apr 02 '11 at 07:18
  • Well actually i was a bit too fast in posting as I did not notice that you wanted the inputs resat, I just thought that you wanted to clear the TD's – Kenneth Jakobsen Apr 04 '11 at 08:37
0

In the first for loop, just add this:

cInp[i].value='';
Anthony
  • 12,177
  • 9
  • 69
  • 105
Porco
  • 4,163
  • 3
  • 22
  • 25