-3

I have many checkboxes with prices. I want that every time the user selects a checkbox, the final price is updated. I have done it with JQuery but the function is never entered.

$('input[type=checkbox]:checked').on('change', function() {
    console.log("Hi")
    var total = 0;
    var result = document.getElementById('result');

    if ($('checkbox1').prop("checked")) {
        total += 100;
    }

    if ($('checkbox2').prop("checked")) {
        total += 50;
    }

    if ($('checkbox3').prop("checked")) {
        total += 250;
    }

    result.innerText = 'Result: ' + total + '€';
});

HTML:

<input type="checkbox" name="myCheckbox" id="checkbox1" value="yes"/> 7:30h-21:00h - 250€
<div id="result"><p>Result: </p></div>

I would also like to know if there is something like:

$('input[type=checkbox]:checked').on('change', function() || $('#num').on("keyup", function() {

Because I want it to enter the function whether a checkbox has been selected or if it has selected a number in the input:number.

  • Instead of the superfluous value "yes", give a meaningful value to the checkboxes (the number you're currently adding). Then just read the value, and add it to `total` variable declared in the outer scope, or reduce when the box is unchecked. – Teemu Jan 11 '23 at 12:32
  • `$('input[type=checkbox]:checked').on` will only apply to the checkboxes that are *checked when that code runs* - checking them later then unchecking would not fire this event. Instead, use `$('input[type=checkbox]').on("change", ":checked', function()...` – freedomn-m Jan 11 '23 at 13:00

1 Answers1

0

I think .on() function in jQuery's newer version is obsolete now try this way.

$('input[type="checkbox"]').change(function () {
    console.log("Hi")
    var total = 0;
    var result = document.getElementById('result');

    if ($('checkbox1').prop("checked")) {
        total += 100;
    }
    if ($('checkbox2').prop("checked")) {
        total += 50;
    }
    if ($('checkbox3').prop("checked")) {
        total += 250;
    }
    result.innerText = 'Result: ' + total + '€';
});