简体   繁体   中英

Calculate total price based on checkboxes

I want when someone click on checkbox this price adding in to total price. Or button will be better?

I use Django models and form for visual on HTML.

 $(document).ready(function() { const ID_CHECK_1 = 'id_checkbox_1'; const ID_CHECK_2 = 'id_checkbox_2'; const ID_CHECK_3 = 'id_checkbox_3'; const ID_PRICE_1 = 'id_price_1'; const ID_PRICE_2 = 'id_price_2'; const ID_PRICE_3 = 'id_price_3'; const ID_TOTAL_PRICE = 'id_total_price'; var $check1 = $('#' + ID_CHECK_1); var $check2 = $('#' + ID_CHECK_2); var $check3 = $('#' + ID_CHECK_3); var $price1 = $('#' + ID_PRICE_1); var $price2 = $('#' + ID_PRICE_2); var $price3 = $('#' + ID_PRICE_3); var $total = $('#' + ID_TOTAL_PRICE); var totalPrice = $total.val(); $($check1).click(function() { if ($check1.is(":checked")) { totalPrice += parseFloat($price1.val()); } if ($check2.is(":checked")) { totalPrice += Number($price2.val()); } if ($check3.is(":checked")) { totalPrice += Number($price3.val()); } }) });

Why not declare your variables simpler. Not really necessary to save the ID as a constant when you only need the element anyways.

    var check1 = $('#id_checkbox_1');
    var check2 = $('#id_checkbox_2');
    var check3 = $('#id_checkbox_3');

    var price1 = $('#id_price_1');
    var price2 = $('#id_price_2');
    var price3 = $('#id_price_3');

    var total = $('#id_total_price');

    var totalPrice = total.val();

is there a reason you prepend $ to your variable names? I am not familiar with django, but in Javascript / JQuery $ refers to jQuery and should not be used in variable names.

You also only add an event listener on one element, check1. Assuming you want a checked element to add to the current price and removing itself as soon as unchecked:

$('input:checkbox).off('click').on('click', function() {
    // selects all <div> elements with checkbox attribute and adds click listener
    // off() prevents event listeners stacking
    if ($(this).is(":checked")) {
        // $(this) refers to the element the event occured on
        totalVal += currentprice;
    } else {
        totalVal -= currentprice;
    }
});

Don't forget your semicolons!

Now assuming you have more than three priced elements you want to include, it would be useful to connect element and price. currently you grab your elements and prices via id. How does your HTML structure look?

For calculating a price, you could store the number in a data attribute.

// set price
check1.data('price', 235.5);

// read price 
var price1 = check1.data('price');

Or you create objects. The exact code you need strongly depends on your HTML structure and what you exactly want to do.

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