Reputation:
This is my javascript to copy row and remove row
function cloneRow()
{
var row = document.getElementById("r1");
var table = document.getElementById("t1");
var clone = row.cloneNode(true);
clone.id = "newID";
table.appendChild(clone);
}
function removeRowFromTable()
{
var tbl = document.getElementById('div1');
var lastRow = tbl.rows.length;
if (lastRow > 1) tbl.deleteRow(lastRow - 1);
}
and this is my table:
<table id="div1" style="display:none">
<tbody id="t1">
<tr id="r1"><td>
<form:input path="hostname" value="hostname" onfocus="if(this.value == 'hostname'){this.value =''}" onblur="if(this.value == ''){this.value ='hostname'}" size="30" maxlength="30"/>
<form:input path="directory" value="directory" onfocus="if(this.value == 'directory'){this.value =''}" onblur="if(this.value == ''){this.value ='directory'}" size="15" maxlength="15"/>
<form:input path="username" value="username" onfocus="if(this.value == 'username'){this.value =''}" onblur="if(this.value == ''){this.value ='username'}" size="15" maxlength="15"/>
<form:input path="password" value="password" onfocus="if(this.value == 'password'){this.value =''}" onblur="if(this.value == ''){this.value ='password'}" size="15" maxlength="15"/></td></tr>
</tbody>
<input type="button" onclick="cloneRow()" value="+" />
<input type="button" onclick="removeRowFromTable();" value="-" />
</table>
code is working to add or remove the rows dynamically..but, how can I know they are creating with unique ids..i need to save the values to database later on
Upvotes: 1
Views: 1783
Reputation: 4190
You can use also use jquery to get the last id (provided your rows are assigned id in ascending order) and then increment based on that
var highestId = parseInt($("tr:last").attr("id"));
clone.id = ++highestId ;
Upvotes: 0
Reputation: 219986
Use a closure with a local variable:
var cloneRow = (function()
{
var id_num = 0;
return function ()
{
var row = document.getElementById("r1");
var table = document.getElementById("t1");
var clone = row.cloneNode(true);
clone.id = "newID" + id_num++;
table.appendChild(clone);
};
}());
Upvotes: 2