Назначение и обновление значения для динамически создаваемых тегов ввода - jquery - PullRequest
0 голосов
/ 09 июля 2020

Здравствуйте, у меня есть последняя версия jquery, и у меня есть одна таблица, как показано ниже, где, нажимая кнопку добавления, я добавляю строку входных данных, я хочу вычислить общую стоимость каждого конкретного (продукта) при нажатии клавиши (т.е. price = total price), я столкнулся с проблемой, потому что у меня есть динамически добавляемые входные данные в строке, пожалуйста, предложите любое решение для того же.

Примечание: я хочу достичь решения с помощью jquery / javascript

table where i am appending input row

image

 $(function () {
       $("#btnAdd").bind("click", function () {
           var div = $("<tr  />");
           div.html(GetDynamicTextBox(""));
           $("#TextBoxContainer").append(div);
       });
       $("body").on("click", ".remove", function () {
           $(this).closest("tr").remove();
       });
   });
   function GetDynamicTextBox(value) {
       return '<td><input name = "particular[]" type="text" class="form-control" placeholder="Particulars" required /></td>'+ '<td><input name = "hsn[]" type="text" class="form-control" placeholder="HSN" required /></td>' + '<td><input name = "qty[]" type="number" class="form-control qty" placeholder="Quantity" required /></td>' + '<td><input name = "price[]" type="number" class="form-control price" placeholder="Price" required /></td>' + '<td><input name = "total[]" type="number" class="form-control total" placeholder="Total" required /></td>'  + '<td><button type="button" class="btn btn-sm btn-danger remove" data-toggle="tooltip" data-original-title="Remove materials items"><i class="fa fa-trash"></i></button></td>'
   }
<table class="table table-striped table-bordered" id="particulars_table">
  <thead>
     <tr>
        <td>Particular</td>
        <td>HSN</td>
        <td>Qty</td>
        <td>Rate</td>
        <td>Action</td>
     </tr>
  </thead>
  <tbody id="TextBoxContainer">
  </tbody>
  <tfoot>
     <tr>
        <th colspan="5">
           <button id="btnAdd" type="button" class="btn btn-sm btn-success w-100" data-toggle="tooltip" data-original-title="Add more Materials"><i class="glyphicon glyphicon-plus-sign"></i>Add</button>
        </th>
     </tr>
  </tfoot>
</table>

1 Ответ

0 голосов
/ 09 июля 2020

Вы можете использовать keyup и change методы jquery, то есть: всякий раз, когда значение количества изменяется, получите это значение, и мы будем использовать $(this) для получения требуемого tr, используя это, мы получим значение цены и умножьте qty и price вместе и присвойте значение входу total.

Код демонстрации :

$(function() {
  $("#btnAdd").bind("click", function() {
    var div = $("<tr  />");
    div.html(GetDynamicTextBox(""));
    $("#TextBoxContainer").append(div);
  });
  $("body").on("click", ".remove", function() {
    $(this).closest("tr").remove();
  });
});

function GetDynamicTextBox(value) {
  return '<td><input name = "particular[]" type="text" class="form-control" placeholder="Particulars" required /></td>' + '<td><input name = "hsn[]" type="text" class="form-control" placeholder="HSN" required /></td>' + '<td><input name = "qty[]" type="number" class="form-control qty" placeholder="Quantity" required /></td>' + '<td><input name = "price[]" type="number" class="form-control price" placeholder="Price" required /></td>' + '<td><input name = "total[]" type="number" class="form-control total" placeholder="Total" required /></td>' + '<td><button type="button" class="btn btn-sm btn-danger remove" data-toggle="tooltip" data-original-title="Remove materials items"><i class="fa fa-trash"></i></button></td>'
}

 var rowtoatal = 0;
//on change of qty
$(document).on('change keyup ', '.qty ', function() {

//get qty value
  var qty = $(this).val();
  //getting closest tr
  var elem = $(this).closest("tr");
  //get  price value
  var price = elem.find("td input.price").val();
  //check if price is not null
  if (price !== null && price !== '') {
    rowtoatal = qty * price;
    console.log(qty + " *  " + price + " = " + rowtoatal)
    //adding total to sub_total
    elem.find("td input.total").val(rowtoatal)

  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<table class="table table-striped table-bordered" id="particulars_table">
  <thead>
    <tr>
      <td>Particular</td>
      <td>HSN</td>
      <td>Qty</td>
      <td>Rate</td>
      <td>Action</td>
    </tr>
  </thead>
  <tbody id="TextBoxContainer">
  </tbody>
  <tfoot>
    <tr>
      <th colspan="5">
        <button id="btnAdd" type="button" class="btn btn-sm btn-success w-100" data-toggle="tooltip" data-original-title="Add more Materials"><i class="glyphicon glyphicon-plus-sign"></i>Add</button>
      </th>
    </tr>
  </tfoot>
</table>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...