2016-02-12 53 views
1

我有一個按鈕來克隆一行。我想找到一個輸入,然後更改它的ID。如何在我的克隆行中找到特定元素並更改jquery中元素的ID

我的功能:

function cloneRow(tables, rows) { 
     var row = document.getElementById(rows); // find row to copy 
     var table = document.getElementById(tables); // find table to append to 
     var clone = row.cloneNode(true); // copy children too 
     clone.id = rows; // change id or other attributes/contents 
     table.appendChild(clone); // add new row to end of table 
} 

我行進行克隆:

<tr id="row"> 
    <td width="5%"><button type="button" onclick="cloneRow('table', 'row')" class="btn btn-sm btn-info">Add</button></td> 
    <td><button type="button" onclick="removeRow2('table')" class="btn btn-sm btn-danger">Remove</button></td> 
    <td width="20%"><input type="text" required class="form-control" name="txtitemname[]" /></td> 
    <td width="30%"><input type="text" class="form-control" name="txtnote[]" placeholder="e.g. box of milk, bottles of water" /></td> 
    <td width="20%"><input type="text" class="form-control" style="background-color:#FFF" id="expiration-date" name="txtexpiration[]" /></td> 
    <td><input type="number" required min="1" value="1" class="form-control" name="txtquantity[]" /></td> 
</tr> 

我想,當它被克隆有效期限的ID更改爲到期,日期1。

回答

1
<!DOCTYPE html> 
<html> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> 


<script> 
    $(document).ready(function() { 




    }); 
    function cloneRow() { 
     var objRow; 
     objRow = $('#row').clone(); 
     $(objRow).find('#expiration-date').attr('id', 'expiration-date' + $('#tbl_sample tr').length); 
     $(objRow).attr('id', 'row_' + $('#tbl_sample tr').length) 
     $('#tbl_sample').append($(objRow)); 
    } 

</script> 



<body> 
    <table id="tbl_sample"> 

     <tr id="row"> 
    <td width="5%"><button type="button" onclick="cloneRow()" class="btn btn-sm btn-info">Add</button></td> 
    <td><button type="button" onclick="removeRow2('table')" class="btn btn-sm btn-danger">Remove</button></td> 
    <td width="20%"><input type="text" required class="form-control" name="txtitemname[]" /></td> 
    <td width="30%"><input type="text" class="form-control" name="txtnote[]" placeholder="e.g. box of milk, bottles of water" /></td> 
    <td width="20%"><input type="text" class="form-control" style="background-color:#FFF" id="expiration-date" name="txtexpiration[]" /></td> 
    <td><input type="number" required min="1" value="1" class="form-control" name="txtquantity[]" /></td> 
</tr> 
    </table> 
</body> 
</html> 
+0

如何在每次克隆時增加它?如果我有到期日期2,則下一個將到期日期3。 –

+0

已經完成。檢查:) – Aswathy

+0

謝謝先生:)。你節省了我的一天:) –