jQuery add rows to table
by Ondrej
HTML
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
<script src="//code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- For demo purpose -->
<div class="container text-center text-white">
<div class="row pt-5">
<div class="col-lg-8 mx-auto">
<h1 class="display-4">jQuery add rows to table</h1>
<p class="font-italic mb-0">Using jquery & Bootstrap 4, dynamically add and remove table rows. </p>
<p class="font-italic">Snippet by
<a class="text-white" href="https://bootstrapious.com/snippets">
<u>Bootstrapious</u>
</a>
</p>
</div>
</div>
</div>
<div class="container py-5">
<div class="row">
<div class="col-lg-7 mx-auto">
<div class="card rounded-0 border-0 shadow">
<div class="card-body p-5">
<!-- Bootstrap table-->
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">First</th>
<th scope="col">Last</th>
<th scope="col">Handle</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td>Mark</td>
...
CSS
/*
*
* ==========================================
* FOR DEMO PURPOSES
* ==========================================
*
*/
body {
background: #0083B0;
background: -webkit-linear-gradient(to right, #0083B0, #00B4DB);
background: linear-gradient(to right, #0083B0, #00B4DB);
min-height: 100vh;
}
.form-control::placeholder {
font-style: italic;
font-size: 0.85rem;
color: #aaa;
}
JavaScript
$(function () {
// Start counting from the third row
var counter = 3;
$("#insertRow").on("click", function (event) {
event.preventDefault();
var newRow = $("<tr>");
var cols = '';
// Table columns
cols += '<th scrope="row">' + counter + '</th>';
cols += '<td><input class="form-control rounded-0" type="text" name="firstname" placeholder="First name"></td>';
cols += '<td><input class="form-control rounded-0" type="text" name="lastname" placeholder="Last name"></td>';
cols += '<td><input class="form-control rounded-0" type="text" name="handle" placeholder="Handle"></td>';
cols += '<td><button class="btn btn-danger rounded-0" id ="deleteRow"><i class="fa fa-trash"></i></button</td>';
// Insert the columns inside a row
newRow.append(cols);
// Insert the row inside a table
$("table").append(newRow);
// Increase counter after each row insertion
counter++;
});
// Remove row when delete btn is clicked
$("table").on("click", "#deleteRow", function (event) {
$(this).closest("tr").remove();
counter -= 1
});
});