"Dynamically add and remove row from table"
Bootstrap 3.3.0 Snippet by guilofrano

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<!------ Include the above in your HEAD tag ---------->
<table class="table" id="myTable">
<thead>
<tr>
<th>
Header
</th>
</tr>
</thead>
<tbody>
<tr id="row0">
<td>
<div class="input-group">
<input type="text" class="form-control" />
<span class="input-group-btn">
<button id="btn0" type="button" class="btn btn-primary" onclick="addRow(this)">
<span id="icon0" class="glyphicon glyphicon-plus"></span>
</button>
</span>
</div>
</td>
</tr>
</tbody>
</table>
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function addRow(input) {
var table = document.getElementById("myTable");
var i = parseInt(input.id.substring(3, input.id.length));
document.getElementById('icon' + i).className = "glyphicon glyphicon-minus";
var row = table.insertRow(table.rows.length);
row.id = "row" + (i + 1);
var cell = row.insertCell(0);
cell.innerHTML = '<div class="input-group">'+
'<input type="text" class="form-control" />'+
'<span class="input-group-btn">'+
'<button id="btn'+(i+1)+'" type="button" class="btn btn-primary" onclick="addRow(this)">'+
'<span id="icon'+(i+1)+'" class="glyphicon glyphicon-plus"></span>'+
'</button>'+
'</span>'+
'</div>';
$('#btn'+i).attr('onclick', 'remRow(this)');
}
function remRow(input) {
var table = document.getElementById("myTable");
var i = parseInt(input.id.substring(3, input.id.length));
var ind = table.rows["row" +i].rowIndex;
table.deleteRow(ind);
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Related: See More


Questions / Comments: