[javascript] 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?

This question is related to javascript jquery event-handling

The answer is


Try this "html-approach" which is acceptable for small JS projects

_x000D_
_x000D_
function msg(animal,is) {
  console.log(animal, is.checked);   // Do stuff
}
_x000D_
<input type="checkbox" oninput="msg('dog', this)" />Do you have a dog? <br>
<input type="checkbox" oninput="msg('frog',this)" />Do you have a frog?<br>
...
_x000D_
_x000D_
_x000D_


perhaps this may be an alternative for you.

<input name="chkproperty" onchange="($(this).prop('checked') ? $(this).val(true) : $(this).val(false))" type="checkbox" value="true" />`

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.


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

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.

_x000D_
_x000D_
$postList = $('#post-list');_x000D_
_x000D_
$postList.find('h1').on('click', onH1Clicked);_x000D_
_x000D_
function onH1Clicked() {_x000D_
  alert($(this).text());_x000D_
}_x000D_
_x000D_
// simulate added content_x000D_
var title = 2;_x000D_
_x000D_
function generateRandomArticle(title) {_x000D_
  $postList.append('<article class="post"><h1>Title ' + title + '</h1></article>');_x000D_
}_x000D_
_x000D_
setTimeout(generateRandomArticle.bind(null, ++title), 1000);_x000D_
setTimeout(generateRandomArticle.bind(null, ++title), 5000);_x000D_
setTimeout(generateRandomArticle.bind(null, ++title), 10000);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<section id="post-list" class="list post-list">_x000D_
  <article class="post">_x000D_
    <h1>Title 1</h1>_x000D_
  </article>_x000D_
  <article class="post">_x000D_
    <h1>Title 2</h1>_x000D_
  </article>_x000D_
</section>
_x000D_
_x000D_
_x000D_

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.

_x000D_
_x000D_
$postList = $('#post-list');_x000D_
_x000D_
$postList.on('click', 'h1', onH1Clicked);_x000D_
_x000D_
function onH1Clicked() {_x000D_
  alert($(this).text());_x000D_
}_x000D_
_x000D_
// simulate added content_x000D_
var title = 2;_x000D_
_x000D_
function generateRandomArticle(title) {_x000D_
  $postList.append('<article class="post"><h1>Title ' + title + '</h1></article>');_x000D_
}_x000D_
_x000D_
setTimeout(generateRandomArticle.bind(null, ++title), 1000); setTimeout(generateRandomArticle.bind(null, ++title), 5000); setTimeout(generateRandomArticle.bind(null, ++title), 10000);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<section id="post-list" class="list post-list">_x000D_
  <article class="post">_x000D_
    <h1>Title 1</h1>_x000D_
  </article>_x000D_
  <article class="post">_x000D_
    <h1>Title 2</h1>_x000D_
  </article>_x000D_
</section>
_x000D_
_x000D_
_x000D_


Try this jQuery validation

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('#myform').validate({ // initialize the plugin_x000D_
    rules: {_x000D_
      agree: {_x000D_
        required: true_x000D_
      }_x000D_
_x000D_
    },_x000D_
    submitHandler: function(form) {_x000D_
      alert('valid form submitted');_x000D_
      return false;_x000D_
    }_x000D_
  });_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.js"></script>_x000D_
_x000D_
<form id="myform" action="" method="post">_x000D_
  <div class="buttons">_x000D_
    <div class="pull-right">_x000D_
      <input type="checkbox" name="agree" /><br/>_x000D_
      <label>I have read and agree to the <a href="https://stackexchange.com/legal/terms-of-service">Terms of services</a> </label>_x000D_
    </div>_x000D_
  </div>_x000D_
  <button type="submit">Agree</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_


Just another solution

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

Is very simple, this is the way I use:

JQuery:

$(document).on('change', '[name="nameOfCheckboxes[]"]', function() {
    var checkbox = $(this), // Selected or current checkbox
        value = checkbox.val(); // Value of checkbox

    if (checkbox.is(':checked'))
    {
        console.log('checked');
    }else
    {
        console.log('not checked');
    }
});

Regards!


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();
}

This is the solution to find is the checkbox is checked or not. Use the #prop() function//

$("#c_checkbox").on('change', function () {
                    if ($(this).prop('checked')) {
                        // do stuff//
                    }
                });

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to event-handling

How to call function on child component on parent events How to use onClick with divs in React.js Touch move getting stuck Ignored attempt to cancel a touchmove Calling one method from another within same class in Python How to get a right click mouse event? Changing EventArgs to MouseEventArgs causes an error in Form1Designer? How to use the DropDownList's SelectedIndexChanged event Android Overriding onBackPressed() How to pass event as argument to an inline event handler in JavaScript? Get clicked element using jQuery on event? How can I show a hidden div when a select option is selected?