html
JavaScript
x
<table class="table table-bordered listable">
<thead>
<tr class="text-center">
<th>name</th>
<th>amount</th>
<th style="text-align:center">
<a href="#" class="btn btn-info addRow">+</a>
</th>
</tr>
</thead>
<tbody class="text-center">
<tr class="cb" id="row_0">
<td width="20%">
<select class="form-control select2 firstname v1" id="name1_0" name="name[]" style="width: 100%;">
<option id="1">tan</option><option id="2">lim</option>
</select></td>
<td width="20%"><input type="number" name="winlose[]" id="amt1_0" class="form-control first"></td>
<td width="20%"><a href="#" class="btn btn-danger remove">-</a></td>
</tr>
</tbody>
</table>
<button type="button" class="btn btn-primary savebtn">Save</button>
Jquery
JavaScript
$('.addRow').on('click', function(){
addRow();
});
function addRow()
{
var rowCount = $('.listable tr').length -1;
var tr = '<tr class="cb" id="row_'+rowCount+'"><td>';
tr += '<select class="form-control select2" id="name1_'+rowCount+' first" name="name[]">';
tr += '<option id="1">tan</option><option id="2">lim</option></select></td>';
tr += '<td><input type="number" name="winlose[]" id="amt1_'+rowCount+'" class="form-control"></td>';
tr += '<td style="text-align:center"><a href="#" class="btn btn-danger remove">-</a>';
tr += '</td></tr>';
i++;
$('tbody').append(tr);
}
$('tbody').on('click', '.remove', function(){
$(this).parent().parent().remove();
});
$('.savebtn').on('click', function(){
$('.listable .cb').each(function(index, item){
console.log($('#amt1_'+index).val());
});
});
https://jsfiddle.net/u3hmfc7x/1/
This will dynamically add table rows or delete the row when I click the button. After that, if user deleting the second row, then the row id 2 has been deleted and row id should be interchanged dynamically. Does anyone know how to fix this :(?
For example
JavaScript
<tr class="cb" id="row_0"><td>a</td></tr>
<tr class="cb" id="row_1"><td>b</td></tr>
<tr class="cb" id="row_2"><td>c</td></tr>
If user delete the second, the rest will auto sequence back the ID, it will become as below
JavaScript
<tr class="cb" id="row_0"><td>a</td></tr>
<tr class="cb" id="row_1"><td>c</td></tr>
Advertisement
Answer
I think a wiser option, instead of changing the ID, would be to swap the values. You can do that by changing your onclick
for delete operation to:
JavaScript
$('tbody').on('click', '.remove', function(){
elements = $(".cb");
current = parseInt($(this).id);
for (let itr = current; itr < elements.length - 1; itr++) {
elements[itr].value = elements[itr + 1].value;
}
elements[elements.length - 1].remove();
i--;
});
Here’s the code for that: https://jsfiddle.net/ckpLqs4g/