how get checkbox if checked in jquery

How to Get Checkbox if Checked in jQuery

If you want to get the value of a checkbox when it is checked using jQuery, you can use the following code:


$(document).ready(function(){
  $('#checkbox-id').change(function(){
    if(this.checked){
      var checkboxValue = $(this).val();
      console.log('Checkbox is checked and its value is ' + checkboxValue);
    }
  });
});

This code creates an event listener for the checkbox with the ID 'checkbox-id'. When the checkbox is changed (i.e. checked or unchecked), the function inside the change() method is executed. Inside this function, we check if the checkbox is checked using the 'this.checked' property. If it is checked, we get the value of the checkbox using the 'val()' method and store it in a variable called 'checkboxValue'. Finally, we log a message to the console that includes the value of the checked checkbox.

If you have multiple checkboxes, you can use a class selector instead of an ID selector to target all of them, like this:


$(document).ready(function(){
  $('.checkbox-class').change(function(){
    if(this.checked){
      var checkboxValue = $(this).val();
      console.log('Checkbox is checked and its value is ' + checkboxValue);
    }
  });
});

This code is similar to the previous example, but instead of targeting a specific checkbox by ID, we're targeting all checkboxes with a class of 'checkbox-class'. When one of these checkboxes is checked, the function inside the change() method is executed and we get the value of that checkbox.

Overall, getting the value of a checked checkbox in jQuery is a simple process that can be accomplished using the 'change()' method and the 'val()' method.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe