1

I would like that whenever you click on a checkbox, a value is printed to the console that corresponds to the state of the checkbox (on/off). I know there are threads with similar titles but all those I've seen don't have clear examples.

Here's what I got so far (Turn on Console and click Add library, JQuery1.8.3):

Attempt 1

This only prints when the page is loaded, I want it to print whenever I click on it.

Attempt 2

This snippet toggles an on and off value whenever I click on the checkbox, but the box doesn't display the tick symbol anymore when it is toggled on.

3
  • Why are you loading two versions of jQuery in your examples? Commented Jan 6, 2013 at 21:42
  • I wasn't even aware of that. Commented Jan 6, 2013 at 21:42
  • 1
    just to explain why attempt#2 doesn't work(although it should): jQuery internally calls event.preventDefault() for the click-event. The default-action for a click on a checkbox is toggling the checked-property. Because of that you shouldn't use toggle() on elements where you want to proceed with the default click-action(e.g. links, submit-buttons etc. ) Commented Jan 6, 2013 at 22:57

4 Answers 4

4

Listen to the change event.

$("#box").change(function(){  
    console.log(this.checked); 
    // console.log( this.checked ? 'on' : 'off' ); 
});
Sign up to request clarification or add additional context in comments.

Comments

2
$("#box").change(function() {
  console.log($(this).prop('checked'));
});

Comments

1

It's pretty easy, you need to use the .val() inside of a click event. Here is the code:

$('input[type="checkbox"]').click(function() {
    if( $(this).is(':checked') ) {
        console.log( $(this).val() );
    } else {
        console.log('no');
    }
});

Here is a working demo. Hope this helps!

Comments

0

You can do like this:

$('#box').click(function()
{
    if ($('#box').is(':checked')){ 
        console.log("on"); 
    }else{ 
        console.log("off");
    }
});

Comments

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.