Search code examples
javascriptjqueryajaxformsevent-handling

How can I populate Textfield using php ajax in each row of a table upon change of another textfield within the row


I have a javascript where upon click of a button a row with two cells is added to the table. One cell has a livesearch textfield and the another cell has a quantity textfield, whose value suppose to dynamically change and/or determined upon click on the livesearch textfiled results.

I have tried somethin but the challenge I am facing is that the value of the dynamically determined textfield of other rows keep retainin the value of the first row textfiled.

So I am seeking for assistance on how to clean-up the script so that each row will respond according to its respective values in the livesearch textfield

<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">instore Availability</th>
        <th style="color:blue">Price/Unit</th>
        <th style="color:blue">Choose Selling Unit(eg:cartons/etc)</th>
        <th style="color:blue">Quantity</th>
        <th style="color:blue">Cummulative Price</th>
        <th style="color:blue"> Delete </th>
      </tr>
    </thead>
    <tbody>
      <tr>
      </tr>
    </tbody>
  </table>
</div>

<script>
//stock transfer dynamic textboxes
$(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 is-warning eqty" type="text" name="stockeqty[]" readonly size="2"></td>';
    html += '</tr>';

    $('#stockTransfer').append(html);


    $(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);
      $(this).parent(".result").empty();

      var tr = $(this).parent(".search-box").parent().parent().parent();

      $.ajax({
        method: "get",
        url: "saleqtyOnFly.php",
        data: {
          item: stock
        },
        success: function(data) {
          tr.find(".eqty").val(data);
        }
      })

    });
  });
});

Solution

  • The reason it's not populating your "quantity" textbox is because inside $(document).on("click", ".result p", function(), tr doesn't contain a jQuery object. That's because $(this).parent(".result").empty(); clears the "result" div, and that means $(this) no longer exists because that points to an element within the "result" div.

    The simple solution is to assign tr before you clear the "result" div:

      $(this).parents(".search-box").find('.stock').val(stock);
      var tr = $(this).parent().parent().parent().parent();
      $(this).parent(".result").empty();
    

    Here's a working demo (just using hard-coded sample data instead of the responses to your AJAX calls):

    $(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 is-warning eqty" type="text" name="stockeqty[]" readonly size="2"></td>';
        html += '</tr>';
    
        $('#stockTransfer').append(html);
    
    
        $(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();
    
          /*$.ajax({
            method: "get",
            url: "saleqtyOnFly.php",
            data: {
              item: stock
            },
            success: function(data) {
              tr.find(".eqty").val(data);
            }
          })*/
          //just dummy data for example purposes:
          tr.find(".eqty").val(123);
        });
      });
    });
    <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">instore Availability</th>
            <th style="color:blue">Price/Unit</th>
            <th style="color:blue">Choose Selling Unit(eg:cartons/etc)</th>
            <th style="color:blue">Quantity</th>
            <th style="color:blue">Cummulative Price</th>
            <th style="color:blue"> Delete </th>
          </tr>
        </thead>
        <tbody>
          <tr>
          </tr>
        </tbody>
      </table>
    </div>