0

I need to add and delete the number "7" based on a user checking a checkbox and then display that number on the page:

var theTotal = 0;

 $("#highlightChk").change(function() {
      var ishchecked= $(this).is(':checked');
      if(!ishchecked)  theTotal -= 7;
      if(ishchecked) theTotal += 7;

}); 

$('#total').text(theTotal); 

When I display the code it is "0" even when I check the checkbox. What am I doing wrong?

1
  • 4
    $('#total').text(theTotal); You need to put this in that change callback. Otherwise you just give #total the init value, but dosen't give it a new value to display when theTotal is changed. Commented Aug 27, 2015 at 14:17

2 Answers 2

2

Place an initial value in #total and each time an operation is being done read the value and parse it and add to or subtract from it. The #total element has to be updated within the change event handler.

$(function() {
    $("#highlightChk").on('change', function() {
        //READ & PARSE existing value
        var total = +$('#total').text();
        //INC-/DECREMENT value accordingly
        total += this.checked ? 7 : -7;
        //UPDATE DOM with new value
        $('#total').text( total ); //<<--- BELONGS INSIDE
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="highlight" id="highlightChk"/> Highlight<br><br>
Total: <div id="total">0</div>

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

Comments

1

You need to put the $('#total').text(theTotal); inside the change method

$("#highlightChk").change(function () {
    var theTotal = 0;
    var ishchecked = $(this).is(':checked');
    if (!ishchecked) theTotal -= 7;
    else theTotal += 7;
    $('#total').text(theTotal);
});

Since theTotal as a global variable is always 0, but when it's inside the local scope of the jquery .change() method you will always get the correct changed value.

FIDDLE DEMO #1

You can also achieve the same result with less code like:-

$("#highlightChk").change(function () {
    $('#total').text(this.checked ? 7 : 0);
});

FIDDLE DEMO #2

1 Comment

perhaps explaining a bit more would be better :)

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.