Search code examples
javascripthtmljquery

How to Increment the value of a cell in a table by 1 using JavaScript?


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>


Solution

  • To ensure that duplicates of the same item are not added to different rows and that the quantity of an existing row is increased instead, we need to modify the code to check if the item already exists in the table before adding a new row. If the item exists, we simply increase the quantity of the existing row.

    $(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" value="1"></td>';
        html += '</tr>';
    
        $('#stockTransfer tbody').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();
          var tr = $(this).closest('tr');
          var qtyInput = tr.find('.qty');
    
          // Check if the stock item already exists in the table
          var exists = false;
          $('#stockTransfer tbody tr').each(function() {
            var currentRowStock = $(this).find('.stock').val();
            if (currentRowStock === stock) {
              exists = true;
              var currentQty = $(this).find('.qty').val();
              $(this).find('.qty').val(parseInt(currentQty) + 1);
            }
          });
    
          if (!exists) {
            $(this).parents(".search-box").find('.stock').val(stock);
            qtyInput.val(1); // Set default quantity to 1
          } else {
            tr.remove(); // Remove the newly added empty row if item already exists
          }
    
          $(this).parent(".result").empty();
        });
      });
    });
    </script>
    <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>