Skip to content

Instantly share code, notes, and snippets.

@mahedi2014
Created May 4, 2015 08:36
Show Gist options
  • Save mahedi2014/aa33ae627036f036134b to your computer and use it in GitHub Desktop.
Save mahedi2014/aa33ae627036f036134b to your computer and use it in GitHub Desktop.
Add more with jquery by div content cloning
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type='text/javascript' src='//code.jquery.com/jquery-2.1.0.js'></script>
<script>//<![CDATA[
//Add a row in "#addedRows" by cloning '#row'
var cloneCount = 1;
$(window).load(function(){
$("#clone").click(function(){
var newRowId = 'addedRows'+ cloneCount++;
var newDeleteId = "deleteId-"+newRowId;
$('#row')
.clone()
.attr('id', newRowId)
.insertAfter($('[id^=addedRows]:last'))
.html( $("#row").html() );
$('[id^=deleteId]:last').attr('id', newDeleteId);
});
});//]]>
//Delete a column when row more than one
function deleteRow(deleteId){
if(cloneCount > 1){
$('#'+deleteId).closest( "td").parent('tr').remove();
cloneCount--;
}
}
</script>
</head>
<body>
<table border='1'>
<thead>
<tr>
<th>Field</th>
<th><button id="clone">Add more</button> </th>
</tr>
</thead>
<tbody>
<!--this id content will be clone.-->
<tr id="row" >
<td >
<select name="txtCategory[]" id="category">
<option value="">Please select</option>
<option value="">Test 1</option>
<option value="">Test 2</option>
</select>
<input type="text" name="input[]">
</td>
<td>
<button id='deleteId' onclick="deleteRow(this.id);" >Delete</button>
</td>
</tr>
<!--cloning here-->
<tr id="addedRows" ></tr>
</tbody>
</table>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment