从动态标签计算for循环中的值

时间:2017-11-21 16:03:15

标签: javascript jquery

我有这个功能,我有一排价格和参加人数可供选择。我正在尝试根据从更改/选择的与会者(1,2,3,4,...)中选择的值计算所有价格的总和。

function paymentTicketChanges() {
  var sumTicketAttendee = 0;
  var sumTicketPrice = 0;

  $('.ticketing-row').each(function(index, el) {
    var me = $(this);
    var attendee = me.find('.payment_number_attendees').val();
    var price = me.find('.payment_ticket_price').val();

    if ((attendee >= 1) && (price >= 1)) {
      sumTicketPrice += Number(price);
      sumTicketAttendee += Number(attendee);
    }

  });

  $('.payment_ticket_total span').text(sumTicketPrice * sumTicketAttendee);
  $('.card-payment #amount').val(sumTicketPrice * sumTicketAttendee);
}

关于如何获得准确结果的一点点。它乘以总结果

1 个答案:

答案 0 :(得分:2)

您将所有价格的总和乘以所有与会者的总和。您想要乘法每行

function paymentTicketChanges() {
  var total = 0;

  $('.ticketing-row').each(function(index, el) {
    var me = $(this);
    // Convert to number early, note the +
    var attendees = +me.find('.payment_number_attendees').val();
    var price = +me.find('.payment_ticket_price').val();

    if ((attendees >= 1) && (price >= 1)) {
      // Do the sum here, add to total
      total += attendees * price;
    }
  });

  // Use total
  $('.payment_ticket_total span').text(total);
  $('.card-payment #amount').val(total);
}

最后可能会在.toFixed(2)上使用total

直播示例:



$("input").on("input", paymentTicketChanges);
paymentTicketChanges();
function paymentTicketChanges() {
  var total = 0;

  $('.ticketing-row').each(function(index, el) {
    var me = $(this);
    // Convert to number early, note the +
    var attendees = +me.find('.payment_number_attendees').val();
    var price = +me.find('.payment_ticket_price').val();

    if ((attendees >= 1) && (price >= 1)) {
      // Do the sum here, add to total
      total += attendees * price;
    }
  });

  // Use total
  $('.payment_ticket_total span').text(total.toFixed(2));
  $('.card-payment #amount').val(total.toFixed(2));
}

<table>
  <tbody>
    <tr>
      <th>Attendees</th>
      <th>Price</th>
    </tr>
    <tr class="ticketing-row">
      <td><input class="payment_number_attendees" value="2"></td>
      <td><input type="text" class="payment_ticket_price" value="29.99"></td>
    </tr>
    <tr class="ticketing-row">
      <td><input type="text" class="payment_number_attendees" value="3"></td>
      <td><input class="payment_ticket_price" value="10.00"></td>
    </tr>
  </tbody>
</table>
<div class="payment_ticket_total">Total: <span></span></div>
<div class="card-payment">Amount: <input type="text" id="amount"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

附注:注意JavaScript编号和财务金额(请参阅:Is floating point math broken?)。

附注2:有很多方法可以从字符串转换为数字。所有内置的内容都有某种缺点(parseIntparseFloat停止在第一个无效字符而不是失败,Number+处理{{1}好像它是0)。 FWIW:

,我已经到了这里
""

附注3:它们无害,但function toNumber(str) { str = str.trim(); return str === "" ? NaN : +str; } 中的内部()完全没必要。 : - )