2

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.

1 Answer 1

5
  • 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

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks Arun , but can you please let me know what does "+this" mean in your code? I mean adding the plus sign before "this"?
@Behseini it is the unary plus operator, I used it to convert the string id to an int value(used it instead of parseInt(this.id))
Thanks but the solution is not working on this Example jsfiddle.net/Behseini/q9V35/4 ! can you please take alook at that and let me know what I am doing wrong there?
@Behseini look at your console there are no variables named newval - jsfiddle.net/arunpjohny/q9V35/5

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.