1

У меня проблема при удалении строки из таблицы. У меня есть функция, которая вычисляет общую цену, суммарную сумму и т. Д., Которая работает нормально.Расчет JavaScript при удалении элементов

Однако, если я удалю строку, она не будет пересчитывать ее, то есть удалить стоимость.

1) Как я могу это исправить?
2) Как я могу получить NaN, чтобы не отображаться в столбце «Общая цена» - FIXED
3) Я не эксперт с JavaScript, поэтому также будет полезно получить помощь по улучшению существующего кода!

EDIT: включены x для удаления строк в фрагменте кода (проблема заключается в том, что вы вводите значения в строке, вычисляет их, а затем, когда вы удаляете строку, она не отображает значения из общего числа)

$(function() { 
 
    $(".calculate-rows").keyup(function(event) { 
 
    var total = 0; 
 
    $(".calculate-rows").each(function() { 
 
     var gtotal = 0; 
 
     $(this).find(".rows").each(function() { 
 
     var qty = parseFloat($(this).find(".quantity").val()); 
 
     var rate = parseFloat($(this).find(".unit-price").val()); 
 
     if (isNaN(qty)) { 
 
      qty = 0; 
 
     } 
 
     if (isNaN(rate)) { 
 
      rate = 0; 
 
     } 
 
     var subtotal = qty * rate; 
 
     var subtotal = qty * rate; 
 
     $(this).find(".total-price").val(subtotal.toFixed(2)); 
 
     if (!isNaN(subtotal)) 
 
      gtotal += subtotal; 
 
     $(".subtotal").html("£" + gtotal.toFixed(2)); 
 
     var discount = $('.discount').val(); 
 
     var discount = ((gtotal/100) * discount); 
 
     var total = (gtotal - discount).toFixed(2); 
 
     if (!isNaN(total)) 
 
      $(".total-price").html("£" + total); 
 
     }); 
 
    }); 
 
    }); 
 
}); 
 

 
var wrapper = $('#addrow'); 
 
var newitem = $('.newitem'); 
 
var removeitem = $('.removeitem'); 
 
$(newitem).click(function(e) { 
 
    e.preventDefault(); 
 
    $newrow = $('<tr class="rows"><td style="border-top: none;"><input class="form-control" type="text" name="name" required></td><td style="border-top: none;"><textarea class="form-control" rows="1" name="description"></textarea></td><td style="border-top: none;"><input class="text-center form-control quantity" type="text" value="" name="quantity"></td><td style="border-top: none;"><input class="text-center form-control unit-price" type="text" value="" name="unit_price"></td><td style="border-top: none;"><input class="form-control text-center total-price" type="text" value="0.00" readonly></td><td style="border-top: none;" class="text-center"><a class="removeitem" href="#"><i class="fa fa-times"></i></a></td></tr>'); 
 
    $(wrapper).append($newrow); 
 
    $newrow.on("click", "a", function(e) { 
 
    e.preventDefault(); 
 
    $(this).parent().parent().remove(); 
 
    }); 
 
}); 
 
$(removeitem).click(function(e) { 
 
    e.preventDefault(); 
 
    $(this).parent().parent().remove(); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"> 
 
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css"> 
 
<div class="table-responsive calculate-rows"> 
 
    <table class="table"> 
 
    <thead> 
 
     <a href="#" class="btn newitem btn-primary tooltip-primary"><i class="fa fa-plus"></i> New Item</a> 
 
     <tr> 
 
     <th style="width:25%;">Item</th> 
 
     <th style="width:41%;">Description</th> 
 
     <th style="width:10%;" class="text-center">Quantity</th> 
 
     <th style="width:10%;" class="text-center">Unit Price (&#163;)</th> 
 
     <th style="width:10%;" class="text-center">Total Price (&#163;)</th> 
 
     <th style="width:4%;"></th> 
 
     </tr> 
 
    </thead> 
 
    <tbody id="addrow"> 
 
     <tr class="rows"> 
 
     <td style="border-top: none;"> 
 
      <input class="form-control" type="text" name="name" required> 
 
     </td> 
 
     <td style="border-top: none;"> 
 
      <textarea class="form-control" rows="1" name="description"></textarea> 
 
     </td> 
 
     <td style="border-top: none;"> 
 
      <input class="text-center form-control quantity" type="text" value="" name="quantity"> 
 
     </td> 
 
     <td style="border-top: none;"> 
 
      <input class="text-center form-control unit-price" type="text" value="" name="unit_price"> 
 
     </td> 
 
     <td style="border-top: none;"> 
 
      <input class="form-control text-center total-price" type="text" value="0.00" readonly> 
 
     </td> 
 
     <td style="border-top: none;" class="text-center"><a class="removeitem" href="#"><i class="fa fa-times"></i></a> 
 
     </td> 
 
     </tr> 
 
     <tr class="rows"> 
 
     <td style="border-top: none;"> 
 
      <input class="form-control" type="text" name="name" required> 
 
     </td> 
 
     <td style="border-top: none;"> 
 
      <textarea class="form-control" rows="1" name="description"></textarea> 
 
     </td> 
 
     <td style="border-top: none;"> 
 
      <input class="text-center form-control quantity" type="text" value="" name="quantity"> 
 
     </td> 
 
     <td style="border-top: none;"> 
 
      <input class="text-center form-control unit-price" type="text" value="" name="unit_price"> 
 
     </td> 
 
     <td style="border-top: none;"> 
 
      <input class="form-control text-center total-price" type="text" value="0.00" readonly> 
 
     </td> 
 
     <td style="border-top: none;" class="text-center"><a class="removeitem" href="#"><i class="fa fa-times"></i></a> 
 
     </td> 
 
     </tr> 
 
     <tr class="rows"> 
 
     <td style="border-top: none;"> 
 
      <input class="form-control" type="text" name="name" required> 
 
     </td> 
 
     <td style="border-top: none;"> 
 
      <textarea class="form-control" rows="1" name="description"></textarea> 
 
     </td> 
 
     <td style="border-top: none;"> 
 
      <input class="text-center form-control quantity" type="text" value="" name="quantity"> 
 
     </td> 
 
     <td style="border-top: none;"> 
 
      <input class="text-center form-control unit-price" type="text" value="" name="unit_price"> 
 
     </td> 
 
     <td style="border-top: none;"> 
 
      <input class="form-control text-center total-price" type="text" value="0.00" readonly> 
 
     </td> 
 
     <td style="border-top: none;" class="text-center"><a class="removeitem" href="#"><i class="fa fa-times"></i></a> 
 
     </td> 
 
     </tr> 
 

 
    </tbody> 
 
    </table> 
 
    <table class="table invoice-table text-right"> 
 
    <tbody class="totals"> 
 
     <tr> 
 
     <td style="border-top: none;">Sub Total:</td> 
 
     <td style="border-top: none;"><strong class="subtotal">&#163;0.00</strong> 
 
     </td> 
 
     </tr> 
 
     <tr> 
 
     <td style="border-top: none;">Discount:</td> 
 
     <td style="width:20%; border-top: none;"> 
 
      <div class="fm-group input-group" style="margin-bottom:0px"> 
 
      <span class="input-group-addon">%</span> 
 
      <input type="number" class="form-control text-right discount" value="0"> 
 
      </div> 
 
     </td> 
 
     </tr> 
 
     <tr> 
 
     <td style="border-top: none;">VAT:</td> 
 
     <td style="border-top: none;"><strong>&#163;0</strong> 
 
     </td> 
 
     </tr> 
 
     <tr> 
 
     <td style="border-top: none;">Amount Due:</td> 
 
     <td style="border-top: none;"><strong class="total-price">&#163;0</strong> 
 
     </td> 
 
     </tr> 
 

 
    </tbody> 
 
    </table> 
 

 
</div>

ответ

1

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

Что касается NaN, просто чтобы убедиться, что, когда текстовые поля для пустые по количеству и удельному расходу, переменные кол-во и скорость должна по умолчанию 0.

$(function() { 
    $(".calculate-rows").keyup(function(event) { 
    calculate(); 
    }); 
}); 

function calculate() { 
    var total = 0; 
    $(".calculate-rows").each(function() { 
     var gtotal = 0; 
     $(this).find(".rows").each(function() { 
     var qty = parseFloat($(this).find(".quantity").val()); 
     var rate = parseFloat($(this).find(".unit-price").val()); 
      if (isNaN(qty)) qty = 0;    
      if (isNaN(rate)) rate = 0; 

     var subtotal = qty * rate; 
     $(this).find(".total-price").val(subtotal.toFixed(2)); 
     if (!isNaN(subtotal)) 
      gtotal += subtotal; 
     $(".subtotal").html("&#163;" + gtotal.toFixed(2)); 
     var discount = $('.discount').val(); 
     var discount = ((gtotal/100) * discount); 
     var total = (gtotal - discount).toFixed(2); 
     if (!isNaN(total)) 
      $(".total-price").html("&#163;" + total); 
     }); 
    }); 
} 

var wrapper = $('#addrow'); 
var newitem = $('.newitem'); 
var removeitem = $('.removeitem'); 
$(newitem).click(function(e) { 
    e.preventDefault(); 
    $newrow = $('<tr class="rows"><td style="border-top: none;"><input class="form-control" type="text" name="name" required></td><td style="border-top: none;"><textarea class="form-control" rows="1" name="description"></textarea></td><td style="border-top: none;"><input class="text-center form-control quantity" type="text" value="" name="quantity"></td><td style="border-top: none;"><input class="text-center form-control unit-price" type="text" value="" name="unit_price"></td><td style="border-top: none;"><input class="form-control text-center total-price" type="text" value="0.00" readonly></td><td style="border-top: none;" class="text-center"><a class="removeitem" href="#"><i class="fa fa-times"></i></a></td></tr>'); 
    $(wrapper).append($newrow); 
    $newrow.on("click", "a", function(e) { 
    e.preventDefault(); 
    $(this).parent().parent().remove(); 
     calculate(); 
    }); 
}); 
$(removeitem).click(function(e) { 
    e.preventDefault(); 
    $(this).parent().parent().remove(); 
    calculate(); 
}); 
+0

Спасибо за что, какие-то идеи, как, когда строка удаляется, она вносит изменения в значения? – cnorthfield

+0

Отлично спасибо вам большое! – cnorthfield

0

Похоже, вы используете устаревший объект JQuery, чтобы получить ваши ценности от ... проверить обновления ваших исходных данных ..

+0

Не могли бы вы рассказать? – cnorthfield

+0

Я думаю, что @sjerp подразумевает использование атрибута data. https://api.jquery.com/jquery.data/ – bondythegreat

0

попытка повторного обжига событие KeyUp как только вы добавить/удалить строку с помощью вызова $(".calculate-rows").keyup();

Смежные вопросы