0

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>

5
  • Are there any errors in your dev console? In what way does your code not work as expected? Commented Jul 11, 2024 at 19:02
  • This question is similar to: Increment input field value with jQuery. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Jul 11, 2024 at 19:25
  • @HereticMonkey It is not the same. What I want to achieve is to stop duplication of items on rows. So if the item already exists in any row, the value of the quantity cell of the row will increase by one. Thereby stopping duplication Commented Jul 11, 2024 at 21:26
  • Please mock the ajax call with a test object Commented Jul 11, 2024 at 21:32
  • @mplungjan done, please check Commented Jul 11, 2024 at 21:52

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

1 Comment

I appreciate it works, I have seen my logical errors
0

You can't use ++ with a function call, it can only be applied to a variable or an expression that references an object property. So change

tr.find(".qty").val() ++;

to

tr.find(".qty")[0].value++;

Indexing a jQuery object returns the corresponding DOM element. This then allows you to refer directly to its value property, rather than calling a function.

Also, when creating the input field, you need to give it an initial value so you can increment it. Put value="0" in the HTML.

$(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="0"></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();
      console.log(stock);
      $(this).parents(".search-box").find('.stock').val(stock);
      var tr = $(this).closest("tr");
      $(this).parent(".result").empty();

      table = document.getElementById("stockTransfer");
      var rows = table.rows;
      for (var i = 1; i < rows.length; i++) {
        console.log(`row ${i}`);
        var cols = rows[i].cells;
        for (var c = 0; c < cols.length; c++) {
          console.log(`col ${c}, ${cols[c].innerText}`);
          if (cols[c].innerText == stock) {
            //return cols[0].innerHTML;
            tr.find(".qty")[0].value++;

          }
        }
      }
    })
  });
})
<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>

6 Comments

its not working
Can you provide a working minimal reproducible example? I can't test with your code because it uses AJAX for the search function. Can you replace that with mock code that works locally?
Where do you initialize the value in .qty so it will be a number that can be incremented?
I have edited the mock
I don't understand what you're doing in the for loop. None of the columns in the table have any inner text to match with if (cols[c].innerText == stock). The table only contains <input> boxes.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.