jQuery checkbox checked state changed event

jQuery checkbox checked state changed event

I want an event to fire client side when a checkbox is checked / unchecked:
$(‘.checkbox’).click(function() {
if ($(this).is(‘:checked’)) {
// Do stuff
}
});

Basically I want it to happen for every checkbox on the page. Is this method of firing on the click and checking the state ok?
I’m thinking there must be a cleaner jQuery way. Anyone know a solution?

Solutions/Answers:

Solution 1:

Bind to the change event instead of click. However, you will probably still need to check whether or not the checkbox is checked:

$(".checkbox").change(function() {
    if(this.checked) {
        //Do stuff
    }
});

The main benefit of binding to the change event over the click event is that not all clicks on a checkbox will cause it to change state. If you only want to capture events that cause the checkbox to change state, you want the aptly-named change event. Redacted in comments

Also note that I’ve used this.checked instead of wrapping the element in a jQuery object and using jQuery methods, simply because it’s shorter and faster to access the property of the DOM element directly.

Edit (see comments)

To get all checkboxes you have a couple of options. You can use the :checkbox pseudo-selector:

$(":checkbox")

Or you could use an attribute equals selector:

$("input[type='checkbox']")

Solution 2:

For future reference to anyone here having difficulty, if you are adding the checkboxes dynamically, the correct accepted answer above will not work. You’ll need to leverage event delegation which allows a parent node to capture bubbled events from a specific descendant and issue a callback.

// $(<parent>).on('<event>', '<child>', callback);
$(document).on('change', '.checkbox', function() {
    if(this.checked) {
      // checkbox is checked
    }
});

Note that it’s almost always unnecessary to use document for the parent selector. Instead choose a more specific parent node to prevent propagating the event up too many levels.

The example below displays how the events of dynamically added dom nodes do not trigger previously defined listeners.

$postList = $('#post-list');

$postList.find('h1').on('click', onH1Clicked);

function onH1Clicked() {
  alert($(this).text());
}

// simulate added content
var title = 2;

function generateRandomArticle(title) {
  $postList.append('<article class="post"><h1>Title ' + title + '</h1></article>');
}

setTimeout(generateRandomArticle.bind(null, ++title), 1000);
setTimeout(generateRandomArticle.bind(null, ++title), 5000);
setTimeout(generateRandomArticle.bind(null, ++title), 10000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="post-list" class="list post-list">
  <article class="post">
    <h1>Title 1</h1>
  </article>
  <article class="post">
    <h1>Title 2</h1>
  </article>
</section>

While this example displays the usage of event delegation to capture events for a specific node (h1 in this case), and issue a callback for such events.

$postList = $('#post-list');

$postList.on('click', 'h1', onH1Clicked);

function onH1Clicked() {
  alert($(this).text());
}

// simulate added content
var title = 2;

function generateRandomArticle(title) {
  $postList.append('<article class="post"><h1>Title ' + title + '</h1></article>');
}

setTimeout(generateRandomArticle.bind(null, ++title), 1000); setTimeout(generateRandomArticle.bind(null, ++title), 5000); setTimeout(generateRandomArticle.bind(null, ++title), 10000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="post-list" class="list post-list">
  <article class="post">
    <h1>Title 1</h1>
  </article>
  <article class="post">
    <h1>Title 2</h1>
  </article>
</section>

Solution 3:

Just another solution

$('.checkbox_class').on('change', function(){ // on change of state
   if(this.checked) // if changed state is "CHECKED"
    {
        // do the magic here
    }
})

Solution 4:

If your intention is to attach event only on checked checkboxes (so it would fire when they are unchecked and checked later again) then this is what you want.

$(function() {
    $("input[type='checkbox']:checked").change(function() {

    })
})

if your intention is to attach event to all checkboxes (checked and unchecked)

$(function() {
    $("input[type='checkbox']").change(function() {

    })
})

if you want it to fire only when they are being checked (from unchecked) then @James Allardice answer above.

BTW input[type='checkbox']:checked is CSS selector.

Solution 5:

$(document).ready(function () {
    $(document).on('change', 'input[Id="chkproperty"]', function (e) {
        alert($(this).val());
    });
});

Solution 6:

Action taking based on an event (on click event).

$('#my_checkbox').on('click',function(){
   $('#my_div').hide();
   if(this.checked){
     $('#my_div').show();
   }
});

Without event taking action based on current state.

$('#my_div').hide();
if($('#my_checkbox').is(':checked')){
  $('#my_div').show();
}