JSFiddle - React, Tailwind, and code Playground
by StepBaro
HTML
<div style="display:inline-block; width: 50px">Code:</div> <input id="code" type="text" />
<br/><br/>
<div style="display:inline-block; width: 50px">Qty:</div> <input id="qty" type="text" />
<br/><br/>
<div style="display:inline-block; width: 50px"></div> <button id="add">Add</button>
<br/><br/><br/>
<table id="productlist" style="width:300px; border:solid 1px black;">
<tbody>
<tr>
<th width='80%' style='border-right:solid 1px black;'>Product Code</th>
<th width='20%'>Qty</th>
</tr>
</tbody>
</table>
JavaScript
$('#add').click(function() {
var c = $('#code').val();
var q = $('#qty').val();
// Important here is the new class='qty'
var $row = $(
"<tr style='text-align: center;'>" +
" <td width='80%' style='border-right:solid 1px black;' >" + c + "</td>" +
" <td class='qty' width='20%'>" + q + "</td>" +
"</tr>"
);
// Check if code exists
var exists = false;
$('#productlist tbody tr').each(function() {
// If exists a product with the same productCode...
if ($(this).data('procode') == c) {
// Flag exists
exists = true;
// Update old quantity internal data
$(this).data('qty', parseInt(q) + parseInt($(this).data('qty')));
// Update table with new value
$('.qty', this).html($(this).data('qty'));
}
});
// If not, we create a new row
if (!exists) {
$row.data("procode", c);
$row.data("qty", q);
$('#productlist tbody').append($row);
}
});
setTimeout(function(){
$('#code').val('Sony');
$('#qty').val('1');
$('#add').click();
}, 2000);
setTimeout(function(){
$('#code').val('Samsung');
$('#qty').val('1');
$('#add').click();
}, 4000);
setTimeout(function(){
$('#code').val('Sony');
$('#qty').val('10');
$('#add').click();
}, 6000);
setTimeout(function(){
$('#code').val('Samsung');
$('#qty').val('1');
$('#add').click();
}, 8000);