if checkbox is checked, do this

android.nick picture android.nick · Nov 22, 2010 · Viewed 405.7k times · Source

When I check a checkbox, I want it to turn <p> #0099ff.

When I uncheck the checkbox, I want it to undo that.

Code I have so far:

$('#checkbox').click(function(){
    if ($('#checkbox').attr('checked')) {
        /* NOT SURE WHAT TO DO HERE */
    }
}) 

Answer

jensgram picture jensgram · Nov 22, 2010

I would use .change() and this.checked:

$('#checkbox').change(function(){
    var c = this.checked ? '#f00' : '#09f';
    $('p').css('color', c);
});

--

On using this.checked
Andy E has done a great write-up on how we tend to overuse jQuery: Utilizing the awesome power of jQuery to access properties of an element. The article specifically treats the use of .attr("id") but in the case that #checkbox is an <input type="checkbox" /> element the issue is the same for $(...).attr('checked') (or even $(...).is(':checked')) vs. this.checked.