Behseini
Behseini

Reputation: 6320

Issue on Adding Values to a Variable in jQuery

Can you please take a look at This Demo and let me know why I am not able to add values to the var result variable in my code? I think I declared the result in a global scope so all methods will have access to it but it is not functioning here for me!

Here is the code I have:

<ul>
    <li><input type="checkbox" id="25" />25</li>
    <li><input type="checkbox" id="50" />50</li>
    <li><input type="checkbox" id="75" />75</li>
</ul>
<div id="result"></div>

and jQuery code:

$(document).ready(function () {
    var result = 0;
    $("#25").on("click", function () {
        var newResult = result + 25;
        $("#result").html(newResult);
    });
    $("#50").on("click", function () {
        var newResult = result + 50;
        $("#result").html(newResult);
    });
    $("#75").on("click", function () {
        var newResult = result + 75;
        $("#result").html(newResult);
    });
});

Thanks.

Upvotes: 2

Views: 81

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

  • First jQuery is not added in the fiddle
  • You are not updating the value of result when an item is selected

Try

$(document).ready(function () {
    var result = 0;
    $("#25, #50, #75").on("change", function () {
        if (this.checked) {
            result += +this.id;
        } else {
            result -= +this.id;
        }
        $("#result").html(result);
    });
});

Demo: Fiddle

Upvotes: 5

Related Questions