// Bind to click event on buttons
$(".btnAdd").on("click", function(){
// Get highest existing number and add 1
let rowNum = parseInt(getHighestNumber()) + 1;
// The next 4 lines should be populated with values from elsewhere
let firstname = "myFirstName";
let lastname = "myLastName";
let city = "myCity";
let country = "myCountry";
// Build HTML to insert
let html = `<tr class="row">
<td>${rowNum}</td>
<td>${firstname}</td>
<td>${lastname}</td>
<td>${city}</td>
<td>${country}</td>
</tr>`;
// Get which button was clicked
let btn = $(this).attr("id");
if (btn=="btnAddAbove") {
// Insert the HTML after the header row, i.e. first in the actual table
$(".header").after(html);
} else if (btn=="btnAddBelow") {
// Append the new row at the end of the table
$("#tbl").append(html);
}
});
function getHighestNumber() {
let highest = 0;
// Select the first column of each row
let firstCol = $("#tbl tr td:first-child");
firstCol.each( function(index) {
// Get number in first column
let num = $(this).html();
if (num > highest) {
highest = num;
}
});
return highest;
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Get Fiddle Pages with PRO
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.