JQuery Add new item in table

Code sample

—-

Click here to View Demo 

—-

<!DOCTYPE html>
<html>
<head>
<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js”></script&gt;
<style>
table, td {
border: 0px solid black;
}
</style>
</head>
<body>

<p>Click the button to add a new row at the first position of the table and then add cells and content.</p>
<table style=’display:none;border: 1px solid red;’ id=”myTable”>
<tr>
<td><input type=’text’/></td>
<td>
<select>
<option value=”volvo”>Volvo</option>
<option value=”saab”>Saab</option>
<option selected value=”mercedes”>Mercedes</option>
<option value=”audi”>Audi</option>
</select>
</td>
<td><input type=”button” value=”Delete Row”></td>
</tr>

</table>
<div class=”dynamiTbl”>
<table id=”myTableMain”>
<tr>
<th>Month</th>
<th>Savings</th>
<th>Savings</th>
</tr>
<tr>
<td><input type=’text’/></td>
<td>
<select>
<option value=”volvo”>Volvo</option>
<option value=”saab”>Saab</option>
<option selected value=”mercedes”>Mercedes</option>
<option value=”audi”>Audi</option>
</select>
</td>
<td><input type=”button” value=”Delete Row”></td>
</tr>

</table>
</div>
<br>

<button id=’btnAddMore’ onclick=”myFunction()”>Add more</button>

<script>
var totalItem=0;
function myFunction() {
var table = document.getElementById(“myTable”);

var tableMain = document.getElementById(“myTableMain”);

var clone = table.getElementsByTagName(‘tr’)[0].cloneNode(true); // copy children too
if(tableMain.getElementsByTagName(‘tr’).length <= 10)
{
var tds =clone.cells[0];//
var inptText = tds.getElementsByTagName(‘input’);
inptText[0].value=”;
tds =clone.cells[1];//
var inptSelect = tds.getElementsByTagName(‘select’);
inptSelect[0].selectedIndex =-1;

tableMain.appendChild(clone);
}
else
{
$(‘#btnAddMore’).hide();
}

}
$(function(){
//alert(1);
//$(‘input[type=”button”]’).click(function(e){
//$(this).closest(‘tr’).remove();});

$(“.dynamiTbl”).on(“click”, “#myTableMain tr input[type=’button’]”, function(e) {
$(this).closest(‘tr’).remove();
$(‘#btnAddMore’).show();
});

});

</script>

</body>
</html>

Advertisements