предыдущая строка не вычисляется / обновляется из добавленных строк с использованием jquery - PullRequest
0 голосов
/ 23 февраля 2019

нашел этот вопрос, который решил мою проблему раньше и принял базу ответов для моих нужд, динамические формы, несколько полей ввода, вычислили

Но я заметил, когда обновляю сумму предыдущие строки , общая сумма не обновляется.Можете ли вы помочь мне, как решить эту проблему?заранее спасибо!

 $(document).ready(function() {
  var i = 0;
  $("#quantity-" + i).change(function() {
    upd_art(i)
  });
  $("#price-" + i).change(function() {
    upd_art(i)
  });


  $('#add').click(function() {
    i++;
    $('#articles').append('<tr id="row' + i + '"><td><input type="number" value=0 id="quantity-' + i + '" name="quantity[]" placeholder="quantity" class="form-control name_list" /></td> <td><input type="number" id="price-' + i + '" name="price[]" value=0  placeholder="price" class="form-control name_list" /></td> <td><input type="number" id="total-' + i + '" name="total[]" placeholder="total" class="form-control name_list" readonly /></td> <td><button type="button" name="remove" id="' + i + '" class="btn btn-danger btn_remove">X</button></td></tr>');

    $("#quantity-" + i).change(function() {
      upd_art(i)
    });
    $("#price-" + i).change(function() {
      upd_art(i)
    });


  });


  $(document).on('click', '.btn_remove', function() {
    var button_id = $(this).attr("id");
    $('#row' + button_id + '').remove();
  });

  $('#submit').click(function() {
    alert($('#add_name').serialize()); //alerts all values           
    $.ajax({
      url: "wwwdb.php",
      method: "POST",
      data: $('#add_name').serialize(),
      success: function(data) {
        $('#add_name')[0].reset();
      }
    });
  });

  function upd_art(i) {
    var qty = $('#quantity-' + i).val();
    var price = $('#price-' + i).val();
    var totNumber = (qty * price);
    var tot = totNumber.toFixed(2);
    $('#total-' + i).val(tot);
  }



  //  setInterval(upd_art, 1000);
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>

<body>
  <div class="container">
    <br />
    <br />
    <div class="form-group">
      <form name="add_name" id="add_name">
        <div class="table-responsive">
          <table class="table table-bordered" id="articles">
            <tr class="rrjeshta">

              <td><input value=0 type="number" id="quantity-0" name="quantity[]" placeholder="quantity" class="form-control name_list" /></td>
              <td><input value=0 type="number" id="price-0" name="price[]" placeholder="price" class="form-control name_list" /></td>

              <td><input type="number" id="total-0" name="total[]" placeholder="total" class="form-control name_list" readonly /></td>
              <td><button type="button" name="add" id="add" class="btn btn-success">Add new</button></td>
            </tr>
          </table>
          <input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />
        </div>
      </form>
    </div>
  </div>

1 Ответ

0 голосов
/ 23 февраля 2019

Ваша проблема в том, что вы повторно используете i в функции обновления, которая является глобальной переменной.Это означает, что он будет работать только для последней строки, так как каждый раз, когда ваше событие изменения запускает, он обновляет строку, которая соответствует текущему значению i (то есть последней).Вам нужно передать индекс определенной строки в функцию, а не текущее общее количество строк.

Вы можете сделать это, взяв его из вашего существующего ввода id (т.е. удалив общий текст, такой как quantity-) но я бы посоветовал добавить атрибут for для каждого из входов, который соответствует индексу строки.

Вы также можете упростить события щелчка, добавив общие классы к входам, которые будут запускатьпересчет.


Демо

// Be careful when using global variables
var rowCount = 0;

// Minor changes here
// Added "for='i'" for input
// Added .quantity, .price and .total to the relevant inputs
$('#add').click(function() {

  rowCount++;

  $('#articles').append('<tr id="row' + rowCount + '"><td><input type="number" value=0 id="quantity-' + rowCount + '" name="quantity[]" placeholder="quantity" class="form-control name_list quantity" for="' + rowCount + '" /></td> <td><input type="number" id="price-' + rowCount + '" name="price[]" value=0  placeholder="price" class="form-control name_list price" for="' + rowCount + '" /></td> <td><input type="number" id="total-' + rowCount + '" name="total[]" placeholder="total" class="form-control name_list total" for="' + rowCount + '" readonly /></td> <td><button type="button" name="remove" id="' + rowCount + '" class="btn btn-danger btn_remove">X</button></td></tr>');

  // No need to add individual events here

});


// Add a generic event listener for any change on quantity or price classed inputs
$("#articles").on('change', 'input.quantity, input.price', function() {
  upd_art($(this).attr("for"));
});

// No changes
$(document).on('change', 'input', function() {
  var button_id = $(this).attr("id");
  $('#row' + button_id + '').remove();
});

// No changes
$('#submit').click(function() {
  alert($('#add_name').serialize()); //alerts all values           
  $.ajax({
    url: "wwwdb.php",
    method: "POST",
    data: $('#add_name').serialize(),
    success: function(data) {
      $('#add_name')[0].reset();
    }
  });
});


// Using a new index rather than your global variable i
function upd_art(ind) {
  
  var qty = $('#quantity-' + ind).val();
  var price = $('#price-' + ind).val();
  var totNumber = (qty * price);
  var tot = totNumber.toFixed(2);
  $('#total-' + ind).val(tot);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>

<body>
  <div class="container">
    <br />
    <br />
    <div class="form-group">
      <form name="add_name" id="add_name">
        <div class="table-responsive">
          <table class="table table-bordered" id="articles">
            <tr class="rrjeshta">

              <td><input value=0 type="number" id="quantity-0" name="quantity[]" placeholder="quantity" class="form-control name_list quantity" for="0"/></td>
              <td><input value=0 type="number" id="price-0" name="price[]" placeholder="price" class="form-control name_list price" for="0" /></td>

              <td><input type="number" id="total-0" name="total[]" placeholder="total" class="form-control name_list total" for="0" readonly /></td>
              <td><button type="button" name="add" id="add" class="btn btn-success">Add new</button></td>
            </tr>
          </table>
          <input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />
        </div>
      </form>
    </div>
  </div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...