if checkbox is checked, do this if checkbox is checked, do this jquery jquery

if checkbox is checked, do this


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.


Try this.

$('#checkbox').click(function(){    if (this.checked) {        $('p').css('color', '#0099ff')    }}) 

Sometimes we overkill jquery. Many things can be achieved using jquery with plain javascript.


It may happen that "this.checked" is always "on". Therefore, I recommend:

$('#checkbox').change(function() {  if ($(this).is(':checked')) {    console.log('Checked');  } else {    console.log('Unchecked');  }});