April 2017

Dynamically add rows and html controls in table using jQuery

How to add rows dynamically in HTML table with textbox and textarea controls. Example: Download

<html>
<head>
<title>Table Dynamic Row Add Delete Demo</title>
<script src="https://code.jquery.com/jquery-3.2.1.js"
integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous"></script>
</head>
<body>
<div>
<table id="tbl1">
<thead>
<tr>
<th>
Family
</th>
<th>
Address
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="text" id="txtFamil_01" name="txtFamily_01" />
</td>
<td>
<input type="text" id="txtAddress_01" name="txtAddress_01" />
</td>
</tr>
<tr>
<td>
<textarea id="txtFamil_02" name="txtFamily_02"></textarea>
</td>
<td>
<textarea id="txtAddress_02" name="txtAddress_02"></textarea>
</td>
</tr>
</tbody>
</table>
<br />
<button type="button" id="btnAddNewRow">Add New Row</button>
<button type="button" id="btnSave" name="btnSave">Save</button>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#btnAddNewRow").on("click", function () {

var $newRows = $get_lastID();

$(“#tbl1>tbody”).append($newRows);

});

$get_lastID = function () {
var $id = $(‘#tbl1 tbody tr:last-child td:first-child textarea’).attr(“name”);
$lastChar = parseInt($id.substr($id.length – 2), 10);
$lastChar = $lastChar + 1;
var $newRows=””;
$newRow1 = “<tr> \
<td><input type=’text’ name=’txtFamily_0″+ $lastChar + “‘ /></td> \
<td><input type=’text’ name=’txtAddress_0” + $lastChar + “‘ /></td> \ </tr>”

$newRow2 = “<tr> \
<td><textarea type=’text’ name=’txtFamily_0″+ ($lastChar + 1) + “‘></textarea></td> \
<td><textarea type=’text’ name=’txtAddress_0” + ($lastChar + 1) + “‘></textarea></td> \ </tr>”

$newRows = $newRow1+$newRow2;

return $newRows;
}

$(“#btnSave”).on(“click”, function () {
$(“#tbl1 tbody tr”).each(function (i, tr) {

var famil1, famil2, address1, address2;

if (i % 2 === 0) { /* textbox find here*/
famil1 = $(this).find(‘td’).eq(0).find(‘input’).val();
famil2 = $(this).find(‘td’).eq(1).find(‘input’).val();
alert(famil1 + ” ” + famil2);
}
else { /* textarea find here */

address1 = $(this).find(‘td’).eq(0).find(‘textarea’).val();
address2 = $(this).find(‘td’).eq(1).find(‘textarea’).val();
alert(address1 + ” ” + address2);

}

});

});
});
</script>
</body>
</html>