I have the following code where I can move the rows of a table, when adding the raw rows it works great but if I add a row with the button this added row cannot be sorted
Any solution to this code? The method insertRow()
is being misused
$(document).ready(function() {
$("#btn_save_line").click(function() {
var newRow = document.getElementById('tbl_cotizacion').insertRow();
newRow.innerHTML = "<tr><td align='center'>1 </td><td>2</td><td>3</td><td> <span class='glyphicon glyphicon-chevron-up arriba'></span> <span class='glyphicon glyphicon-chevron-down down abajo'> </span></td></tr>";
});
$(".arriba,.abajo").click(function(){
var row = $(this).parents("tr:first");
if ($(this).is(".arriba")) {
row.insertBefore(row.prev());
} else {
row.insertAfter(row.next());
}
});
});
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<button type="button" class="btn btn-primary" id="btn_save_line" >Agregar</button>
<table id="tbl_cotizacion" class="table table-bordered table-sm" cellspacing="0" width="100%">
<thead>
<tr class="table-warning">
<th width="5%"># Indicador</th>
<th width="5%">Cantidad</th>
<th width="10%">Componente</th>
<th width="5%"></th>
</tr>
</thead>
<tbody>
<tr>
<td> </td>
<td> 4 </td>
<td> Falso </td>
<td> <button class='btn btn-danger btn-sm'>x </button> <span class='glyphicon glyphicon-chevron-up arriba'></span> <span class='glyphicon glyphicon-chevron-down down abajo'> </span> </td>
</tr>
<tr>
<td> </td>
<td> 5 </td>
<td> Falso </td>
<td> <button class='btn btn-danger btn-sm'>x </button> <span class='glyphicon glyphicon-chevron-up arriba'></span> <span class='glyphicon glyphicon-chevron-down down abajo'> </span> </td>
</tr>
</tbody>
</table>
For dynamic elements to work, you need to use
.on()
like this: