checkbox on click jquery

Checkbox On Click jQuery

If you want to perform some action when a checkbox is clicked, you can use jQuery to achieve that. Here is how you can do it:

HTML Code


<input type="checkbox" id="myCheckbox">

In the above code, we have created a checkbox with an id "myCheckbox".

jQuery Code


$('#myCheckbox').click(function() {
  if ($(this).is(':checked')) {
    // Checkbox is checked
    // Perform some action here
  } else {
    // Checkbox is not checked
    // Perform some action here
  }
});

In the above code, we have attached a click event handler to the checkbox with id "myCheckbox". When the checkbox is clicked, the function inside the click event handler is called. We are checking if the checkbox is checked or not using the is(':checked') function. If the checkbox is checked, we can perform some action, and if it is not checked, we can perform some other action.

Alternative Method

Another way to achieve the same result is by using the change() function instead of the click() function in jQuery. Here is how you can do it:


$('#myCheckbox').change(function() {
  if ($(this).is(':checked')) {
    // Checkbox is checked
    // Perform some action here
  } else {
    // Checkbox is not checked
    // Perform some action here
  }
});

In the above code, we have attached a change event handler to the checkbox with id "myCheckbox". When the checkbox is changed, the function inside the change event handler is called. We are checking if the checkbox is checked or not using the is(':checked') function. If the checkbox is checked, we can perform some action, and if it is not checked, we can perform some other action.

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