简体   繁体   中英

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. Suppose the default value is 2000, how would I be able to get $amount=2000 (if checked) and $amount remains 0 if unchecked. Due to my limited knowledge in jQuery / JavaScript, I'm unable to find a solution for it. 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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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