简体   繁体   English

jQuery检查输入的增加/减少值

[英]jQuery increase / decrease value on input checked

I'm working on this eCommerce project where I need to calculate "shipping costs" if a particular checkbox is checked. 我正在从事这个电子商务项目,如果选中了特定的复选框,则需要计算“运输成本”。 Here's the code for the checkbox :- 这是复选框的代码:-

<div class="alert alert-info">
<p>Shipping Outside Lagos (N2, 000)</p>
<input type="checkbox" name="shipping" id="shipping">
</div>

How can I write the jQuery function, so that when the input is checked..I can get the value in a variable. 如何编写jQuery函数,以便在检查输入时..我可以在变量中获取值。 Suppose the default value is 2000, how would I be able to get $amount=2000 (if checked) and $amount remains 0 if unchecked. 假设默认值为2000,我将如何获得$ amount = 2000(如果选中),而如果未选中,则$ amount仍为0。 Due to my limited knowledge in jQuery / JavaScript, I'm unable to find a solution for it. 由于我对jQuery / JavaScript的了解有限,因此无法找到解决方案。 Search didn't help either. 搜索也没有帮助。

Any suggestions are welcome. 欢迎任何建议。

var amount = $('#shipping').is(':checked') ? 2000 : 0;

$('#shipping').on('change', function() {
     amount = this.checked ? 2000 : 0;
});

// use amount

You can do: 你可以做:

var shippingAmt = 0;
$("#shipping").change(function() {
    shippingAmt = this.checked ? 2000 : 0;
});

I'd suggest using a function to determine the cost of items. 我建议使用一个函数来确定项目的成本。 You could have an abstract of determining costs which would run through a few or several conditions to calculate 'add ons' so to speak. 您可以具有确定成本的摘要,可以说要花费几个或几个条件才能计算出“附加值”。

So you'd have your initial total of say $500.99, then run that value through something like calculateTotalValue(value) 因此,您的初始总计为$ 500.99,然后通过诸如calculateTotalValue(value)类的值运行该值

It would check if any add-ons were checked in the form, and add their values to the initial value. 它将检查是否在表单中检查了任何附加组件,并将其值添加到初始值。

This would allow you to have any number of extras, like shipping, or even add-ons/upgrades for the product itself, and you'd be able to fetch the total without fail in each case. 这样一来,您可以拥有任意数量的附加产品,例如运输,甚至产品本身的附加组件/升级产品,而且每种情况下您都可以轻松获取总数。 You could have a generic way of stipulating that a field is an 'add on' so you wouldn't need to maintain a list, like so: 您可能有一种通用的方式来规定字段是“附加项”,因此您无需维护列表,例如:

<input type="checkbox" rel="add-on" data-add-on-type="shipping" value="500">

Then in your function, 然后在您的职能中

calculateTotalValue(value) {
    $.each($('input[rel="add-on"]'), function(i) {
        // You probably want some error checking here
        value += this.val();
    });

    return value;
}

If necessary you could use data-add-on-type to keep track of where costs comes from to output a list for the user, as well. 如有必要,您可以使用data-add-on-type来跟踪成本的来源,并为用户输出列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM