开发者

Clone a table row and remove values in JavaScript

开发者 https://www.devze.com 2023-02-21 21:40 出处:网络
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

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.parentNod开发者_StackOverflow中文版e)"></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>


Something like this:

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

for(var i = 0; i <clns.length; i++)
{
   clns[i].innerHTML = "";
}


In the first for loop, just add this:

cInp[i].value='';
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号