0

Quantity、Rate、Total Amount の 3 つのフィールドがあります。いずれかのキーアップ数量またはレート フィールドの場合、合計金額フィールドに金額が表示されます。追加ボタンもあります。誰かが追加ボタンをクリックすると、新しい行と削除リンクが動的に作成されます。私の問題は、数量またはレート フィールドをキー入力すると、calculateSum() 関数が正しく機能することです。2 つの行を作成するとします。合計は 100+(100+100)=300 です。最初のものを削除しても何も変わりません。最後の1つを削除すると、結果は200と表示されますが、正しい結果は100です。ここで間違っている可能性があることを誰かが指摘できますか? どうもありがとう。これが私のコードです:

<html>
    <head>
        <title>Invoice</title>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
      $(document).ready(function() {
$(document).on("keyup",".qty, .rate",function(){
        calculateSum();
    });

$(document).on("click",".del",function(){
        calculateSum();
    });
      });

function calculateSum() {
    var qty = [];
    $(".qty").each(function() {
            var num = parseFloat(this.value) || 1;
            qty.push(num);
    });

    var rate = [];
    $(".rate").each(function() {
            var num = parseFloat(this.value) || 0;
            rate.push(num);
    });
    var total = 0;
    $('input[name="total_amount[]"]').each(function(i){
        var amount = qty[i].toFixed(2)*rate[i].toFixed(2);
        total += amount;
        $(this).val(amount);
    });
    $("#sub_total").text(total);
}
</script>
<script type="text/javascript" language='javascript'>
/*
This script is identical to the above JavaScript function.
*/
var ct = 1;

function new_link()
{
    ct++;
    var div1 = document.createElement('div');
    div1.id = ct;

    // link to delete extended form elements
    var delLink = '<div  style="text-align:right;margin-top:-20px"><a class="del" href="javascript:delIt('+ ct +')">Delete</a></div>';

    div1.innerHTML = document.getElementById('newlinktpl').innerHTML + delLink;

    document.getElementById('newlink').appendChild(div1);

}
// function to delete the newly added set of elements
function delIt(eleId)
{
    d = document;

    var ele = d.getElementById(eleId);

    var parentEle = d.getElementById('newlink');

    parentEle.removeChild(ele);

}
</script>
        <style type="text/css">
table
{
    border: 1px solid black;
    width: 600px;
}


td
{
    border: 1px solid black;
    padding:5px 5px 5px 5px;
}

        </style>
    </head>
    <body>
        <div id="newlink">
        <table cellpadding="0" cellspacing="0">
            <tr>
                <td>Quantity</td>
                <td>Rate</td>
                <td>Total Amount</td>
            </tr>

             <tr>
                 <td><input class='qty' type='text' name='qty[]'/></td>
                <td><input class='rate' type='text' name='rate[]'/></td>
               <td><input class='total_amount' type='text' name='total_amount[]'/></td>
            </tr>

                 </table>
    </div>
        <div id="sub_total">0</div>
        <input type="button" value="Add" onclick="new_link()"/>

                <div id="newlinktpl" style="display:none">
        <table cellpadding="0" cellspacing="0">
          <tr>
                 <td><input class='qty' type='text' name='qty[]'/></td>
                <td><input class='rate' type='text' name='rate[]'/></td>
               <td><input class='total_amount' type='text' name='total_amount[]'/></td>
            </tr>
                 </table>
    </div>
    </body>
</html>
4

5 に答える 5

2

これを試して:

.ready()で:

$(document).on("click",".del", function() {
    // Call delIt before calculateSum() and get id from data attribute.
    delIt($(this).data("id")) 

    calculateSum();
});

new_link()で:

// link to delete extended form elements
var delLink = '<div style="text-align:right;margin-top:-20px"><a class="del" href="#" data-id=' + ct + '>Delete</a></div>';
// Set href = # and set ct to data-id instead.
于 2012-10-11T11:08:44.963 に答える
1

I'd guess your issue is that you have the logic for deletion in the href of the tag, but you're attaching the display update to the click event. The click event will normally be fired before the link is followed, so the display is being updated before the deletion is done. You should consolidate both of these into consistent unobtrusive JavaScript on the click event (add ct to the link dataset). Then you could have a single event handler that dispatches to both functions, or have the delete function call the update function upon completion.

As a note that last sentence above should be a solution even with the existing code, but getting things closer to consistency/expected code wouldn't hurt.

于 2012-10-11T11:24:51.903 に答える
0

ここで私の2セント、@Marioと@MattWhippleの提案を使用してhtmlを書き直しました。また、文字列変数を使用して、ドキュメントの最後にある不要な余分な要素を削除しました。

私は物事を行うためのより良い方法だとは思いませんが、私にとってははるかに明確です。

<html>
  <head>
    <title>Invoice</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript">
      var templateText = '<div><table cellpadding="0" cellspacing="0">\
  <tr>\
    <td><input class="qty" type="text" name="qty[]"/></td>\
    <td><input class="rate" type="text" name="rate[]"/></td>\
    <td><input class="total_amount" type="text" name="total_amount[]"/></td>\
  </tr>\
</table></div>';
      var ct = 1;

      $(document).ready(function() {
        $(document).on("keyup", ".qty, .rate", calculateSum);
        $(document).on("click", ".del", delIt);
      });
      function calculateSum() {
        var total = 0;
        $('#newlink table').each(function(i, e) {
          var that = $(this);
          var qty = parseFloat(that.find('.qty').val()) || 1;
          var rate = parseFloat(that.find('.rate').val()) || 0;
          var amount = qty.toFixed(2)*rate.toFixed(2);
          that.find('.total_amount').val(amount);
          total += amount;
        });
        $("#sub_total").text(total);
      }
      function addRow() {
        ct++;
        var div1 = $(templateText);
        div1.attr('id', ct)
        var delLink = $('<div style="text-align:right;margin-top:-20px"> </div>').append($('<a class="del" href="#" >Delete</a>').data("id", ct));
        div1.append(delLink).appendTo('#newlink');
      }
      function delIt() {
        $('#' + $(this).data("id")).remove();
        calculateSum();
      }
    </script>
  </head>
  <body>
    <div id="newlink">
      <table cellpadding="0" cellspacing="0">
        <tr>
          <th>Quantity</th>
          <th>Rate</th>
          <th>Total Amount</th>
        </tr>
        <tr>
          <td><input class='qty' type='text' name='qty[]'/></td>
          <td><input class='rate' type='text' name='rate[]'/></td>
          <td><input class='total_amount' type='text' name='total_amount[]'/></td>
        </tr>
      </table>
    </div>
    <div id="sub_total">0</div>
    <input type="button" value="Add" onclick="addRow()"/>
  </body>
</html>
于 2012-10-11T13:02:39.557 に答える
0

これを使ってみてください

$(".qty, .rate").live("keyup",function(){
    calculateSum();
});
于 2012-10-11T10:53:25.943 に答える
-2

使用する.bind( eventType [, eventData], handler(eventObject) )

于 2012-10-11T10:57:25.460 に答える