I am developing a point of sale system. Using Javascript, the below code can add a row to my shopping table. However, with button, I can add duplicates of stock to shopping table. So I am considering a situation whereby instead of duplicating same item in rows, the insert query will be not execute. Rather the quantity of the existing row will increase by one. by these, if I scan two pieces of same item, I will only have one row with the quantity cell having 20 value.
For instance, If I select Result 1 twice, it shouldn't insert Result 1 in two different rows but one row with the quantity reading 2.
You can demonstrate the code without my Ajax page.
$(document).ready(function() {
$(document).on('click', '.btnaddstockTransfer', function() {
var html = '';
html += '<tr>';
html += '<td><div class="search-box"><input id="stock" class="form-control is-warning stock" type="text" name="stock[]" placeholder="Search by name or code"><div class="result"></div></div></td>';
html += '<td><input class="form-control qty" type="text" name="qty[]" required size="2"></td>';
html += '</tr>';
$('#stockTransfer').append(html);
// Live Search
$(document).on('keyup input', '.search-box input[type="text"]', function() {
/* Get input value on change */
var inputVal = $(this).val();
var resultDropdown = $(this).siblings(".result");
if (inputVal.length) {
//just dummy data for example purposes:
resultDropdown.html("<p>Result 1</p><p>Result 2</p>");
/*$.get("backend-search.php", {
term: inputVal
}).done(function(data) {
// Display the returned data in browser
resultDropdown.html(data);
});*/
} else {
resultDropdown.empty();
}
});
// Set search input value on click of result item
$(document).on("click", ".result p", function() {
var stock = $(this).text();
$(this).parents(".search-box").find('.stock').val(stock);
var tr = $(this).parent().parent().parent().parent();
$(this).parent(".result").empty();
tr.find(".qty").val(1);
table = document.getElementById("stockTransfer");
var rows = table.rows;
for (var i = 1; i < rows.length; i++) {
var cols = rows[i].cells;
for (var c = 0; c < cols.length; c++) {
if (cols[c].innerText == stock) {
//return cols[0].innerHTML;
tr.find(".qty").val() ++;
}
}
}
})
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<button class="btnaddstockTransfer" type="button">
Add stock transfer
</button>
<div style="overflow-x:auto">
<table id="stockTransfer" class="table">
<thead>
<tr>
<th style="color:blue">Search Product's(Name/Code)</th>
<th style="color:blue">Quantity</th>
</tr>
</thead>
<tbody>
<tr>
</tr>
</tbody>
</table>
</div>