jQuery根据输入数量计算总金额

时间:2017-01-31 17:35:51

标签: javascript jquery html

我正在制作一个表单,用户可以选择jQuery(function($) { var $amount_fields = $('#number-tickets'), $total_amount = $('#total-amount'); $amount_fields.on('input', function(e) { var final_value = 0; $amount_fields.each(function() { var value = $(this).val(); if (!isNaN(value) && value > 0) final_value += parseInt(value); }); $total_amount.val(final_value); }); });字段的多张票,价格固定为$ 5 /票。我想在readonly字段中动态显示总价格。

问题:

  • 默认情况下如何在总金额中显示$ 5?

  • 如果您输入2张门票,应该说是10美元,3张门票是15美元,依此类推。



label, span {
  display: block;
  margin: 5px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
  <span>Number of tickets @ $5/ticket:</span>
  <input type="number" name="number-of-tickets" value="1" min="1" id="number-tickets" />
</label>
<label>
  <span>Total amount:</span>
  $ <input type="text" name="total-amount" value="" id="total-amount" readonly />
</label>
&#13;
var id = "557fba5a8032a674d929e6a1";
Posts.findOne({'_id.str': id});
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

您只需将金额乘以5即可显示正确的总数。请注意.trigger('input')应该传递radix

然后在页面加载时使用jQuery(function($) { var $amount_fields = $('#number-tickets'), $total_amount = $('#total-amount'); $amount_fields.on('input', function(e) { var final_value = 0; $amount_fields.each(function() { var value = $(this).val(); if (!isNaN(value) && value > 0) final_value += parseInt(value,10) * 5; }); $total_amount.val(final_value); }).trigger('input'); });

正确显示

label,
span {
  display: block;
  margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
  <span>Number of tickets @ $5/ticket:</span>
  <input type="number" name="number-of-tickets" value="1" min="1" id="number-tickets" />
</label>
<label>
  <span>Total amount:</span>
  $
  <input type="text" name="total-amount" value="" id="total-amount" readonly />
</label>
super()

答案 1 :(得分:0)

您错过了与门票价格相乘的部分。我在应该照顾的部分发表评论。

&#13;
&#13;
{{1}}
&#13;
{{1}}
&#13;
{{1}}
&#13;
&#13;
&#13;