add colunas
parecido pai filho
by Rapha Souza
HTML
<script src="//code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<link rel="stylesheet" href="//stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
<script src="//stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script language="javascript">
var maximo = 5;
(function($) {
AddTableRow = function() {
var qtd = $("#products-table tbody tr").length;
if (qtd < maximo) {
var newRow = $("<tr>");
var cols = "";
cols += '<td><input class="campo-dinamico" type="text"/></td>';
cols += '<td> </td>';
cols += '<td> </td>';
cols += '<td> </td>';
cols += '<td>';
cols += '<button onclick="RemoveTableRow(this)" type="button">Remover</button>';
cols += '</td>';
newRow.append(cols);
$("#products-table").append(newRow);
resetId();
return false;
}
};
})(jQuery);
(function($) {
RemoveTableRow = function(item) {
var tr = $(item).closest('tr');
tr.fadeOut(0, function() {
tr.remove();
resetId();
});
return false;
}
})(jQuery); //renova os ids dos campos dinâmicos
function resetId() {
$('.campo-dinamico').each(function(i) {
$(this).attr('id', 'campo-' + (i + 1)).val('campo-' + (i + 1));
});
}
</script>
<table id="products-table" border="1">
<thead>
<tr>
<th>Produto</th>
<th>Código</th>
...
CSS
.row {
background: #f8f9fa;
margin-top: 20px;
}
.col {
border: solid 1px #6c757d;
padding: 10px;
}