I have a table whose row is inserted per click of a button. After a row is inserted, the user can live search for item from the input stock
textfield. When searched, if there is correspondence, a result is shown on the .result
div. Upon clicking on any of the .result p
the input stock
textfields gets the selected value. Everything is working out fine.
However, I want to prevent populating the input stock
textfield if the .result p
value is already existing on any of the previous (existing) rows. At that juncture, I want to instead, increase the .qty
cell of the existing row with similar .result p
selected, by 1.
I have done something but being new in JavaScript I am not getting how to go round it.
Please I need an urgent assistance.
You can demonstrate the code without my Ajax page. Thank you
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>78736985</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(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) {
$.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();
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>
</head>
<body>
<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>
</body>
</html>