JSFiddle - React, Tailwind, and code Playground
by Breno RdV
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<button id="add_foo">
Add Foo
</button>
<button id="add_bar">
Add Bar
</button>
<button id="del_foo">
Del Foo
</button>
<button id="del_bar">
Del Bar
</button>
<table id="result" class="table table-dark">
<thead>
<th>Class</th>
<th>Qty</th>
</thead>
<tbody>
</tbody>
</table>
<div id="moreContent">
</div>
<!-- Just so we have something to count-->
<span class="foo"></span>
<span class="foo"></span>
<span class="foo"></span>
<span class="bar"></span>
<span class="bar"></span>
<span class="bar"></span>
<span class="bar"></span>
JavaScript
var tbody = $("table#result tbody");
var div = $("div#moreContent");
let foos = $(".foo");
let bars = $(".bar");
function add_rows(className, qty) {
//Adds a row to the table.
tbody.append(
"<tr><td>"+className+"</td><td id='counter_"+className+"'>"+ qty +"</td></tr>"
);
}
function update_counter(className, diff) {
//Updates the counter for a specific row with classname...
//PS: We're not actually updating by className, but by the string using when while adding a row to the table.
counter = $("td#counter_"+className);
let qty = counter.text();
counter.text(parseInt(qty) + parseInt(diff));
}
$("button#add_foo").click(function(e) {
e.preventDefault();
update_counter("Foo", 1);
});
$("button#add_bar").click(function(e) {
e.preventDefault();
update_counter("Bar", 1);
});
$("button#del_foo").click(function(e) {
e.preventDefault();
$(".foo").first().remove();
update_counter("Foo", -1);
});
$("button#del_bar").click(function(e) {
e.preventDefault();
$(".bar").first().remove();
update_counter("Bar", -1);
});
add_rows("Foo", foos.length);
add_rows("Bar", bars.length);