Jquery checkbox event

jQuery -- Posted on May 15, 2022

This code is a JavaScript/jQuery code snippet. It attaches an event listener to all <input> elements of type "checkbox" within the <body> of an HTML document. When any of these checkboxes are changed (i.e., when a user checks or unchecks them), the function will be executed.

Let's break down the code step by step:

  1. $('body').on('change', 'input[type="checkbox"]', function(e) {

    • $('body'): This part selects the <body> element of the HTML document using the jQuery selector. The event listener is attached to this element.
    • .on('change', 'input[type="checkbox"]', function(e) {: This part adds the 'change' event listener to all <input> elements of type "checkbox" that are descendants of the <body>.
  2. $(this).prop("checked", this.checked);

    • $(this): This part refers to the specific checkbox that triggered the 'change' event.
    • .prop("checked", this.checked): This sets the checked property of the checkbox to the same value as this.checked. In other words, it synchronizes the checked property of the checkbox with the current state of the checkbox after the change event. If the checkbox is checked, it remains checked, and if it's unchecked, it stays unchecked.
  3. $(this).val(this.checked);

    • $(this): Again, this refers to the specific checkbox that triggered the 'change' event.
    • .val(this.checked): This sets the value of the checkbox to the boolean value of this.checked. Since the value attribute of checkboxes is typically used for some sort of data or identifier, this line of code sets the value to either true or false based on whether the checkbox is checked or unchecked.

In summary, the code ensures that when any checkbox within the <body> is changed, its checked property is updated to match its current state, and its value attribute is set to true if checked or false if unchecked. This code snippet is useful if you want to synchronize the checked property and the value attribute of checkboxes to track their state and values accurately.

              
                $('body').on('change', 'input[type="checkbox"]', function(e) {
  $(this).prop("checked", this.checked);
  $(this).val(this.checked);
});
                  
   
            

Related Posts