Reputation: 6320
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
Reputation: 388316
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