我仍在学习 JavaScript,需要帮助更新我的脚本以统计表单中的多个项目。我在我的表单上使用这个脚本来获取单选按钮的值,并将该值添加到事件结帐表单上的“金额”字段。
$(function(){
$('.ticketAmount').click(function() {
$('#Amount').val(this.value);
});
});
现在,我有一个新表格,其中有几个选项可以与选票一起使用。现在,客户选择机票并有几个复选框来添加私有(private)旅游和各种商品。
这是我的 HTML 代码:
<div>
<input type="radio" name="da" value="150" class="ticketAmount" />
<strong>Regular Ticket $150.00</strong>
</div>
<div>
<input type="radio" name="da" value="250" class="ticketAmount" />
<strong>Couples Ticket $250.00</strong>
</div>
<div>
<input type="radio" name="da" value="1500" class="ticketAmount" />
<strong>Table (Seats 10 Individuals) 1500.00</strong>
</div>
<div>
<input type="checkbox" name="da" value="50" class="ticketAddition" >
<strong>Private Tour $50.00</strong>
</div>
<div>
<input type="checkbox" name="da" value="25" class="ticketAddition" >
<strong>Meet the Chef $25.00</strong>
</div>
我希望底部的复选框在选中时将其值添加到总金额中。任何帮助将不胜感激。
最佳答案
当按钮被选中时,将值添加到总数中,然后当按钮未被选中时减去该值。这可以通过 onchange
事件或 .change()
jQuery 方法来完成。
$(function(){
//ticketAmount for radio buttons, ticketAddition for checkboxes
var ticketAmount = 0, ticketAddition = 0;
$(".ticketAmount").change(function() {
//Set ticketAmount to the value of the button checked.
var value = parseInt(this.value);
ticketAmount = value;
$('#amount').text((ticketAmount+ticketAddition)+".00");
});
$(".ticketAddition").change(function() {
//Add or subtract the value of the button from ticketAddition
//depending on whether or not the button has been checked or unchecked.
var value = parseInt(this.value);
if (this.checked) ticketAddition += value;
else ticketAddition -= value;
$('#amount').text((ticketAmount+ticketAddition)+".00");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="radio" name="da" value="150" class="ticketAmount" />
<strong>Regular Ticket $150.00</strong>
</div>
<div>
<input type="radio" name="da" value="250" class="ticketAmount" />
<strong>Couples Ticket $250.00</strong>
</div>
<div>
<input type="radio" name="da" value="1500" class="ticketAmount" />
<strong>Table (Seats 10 Individuals) 1500.00</strong>
</div>
<div>
<input type="checkbox" name="da" value="50" class="ticketAddition" >
<strong>Private Tour $50.00</strong>
</div>
<div>
<input type="checkbox" name="da" value="25" class="ticketAddition" >
<strong>Meet the Chef $25.00</strong>
</div>
<div><strong>Total : $<span id="amount">0.00</span></strong></div>
关于javascript - 获取 JavaScript 表单总量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29750538/