Home > Web Front-end > CSS Tutorial > How to Select All Checkboxes Except for a Specific One with jQuery?

How to Select All Checkboxes Except for a Specific One with jQuery?

DDD
Release: 2024-11-15 00:14:02
Original
840 people have browsed it

How to Select All Checkboxes Except for a Specific One with jQuery?

How to Select All Checkboxes with jQuery Except for a Specific One?

When dealing with jQuery selectors, scenarios arise where you need to select a set of elements while excluding others. In this case, selecting all checkboxes present on a web page, but not a particular one, can be achieved with a few lines of jQuery code.

Given a markup consisting of a table with several input checkboxes, with one checkbox having a unique ID of "select_all," the objective is to select all checkboxes except the "#select_all" checkbox when it is clicked.

jQuery Code:

To accomplish this, you can utilize the following jQuery code:

$('#select_all').change(function() {
  var checkboxes = $(this).closest('form').find(':checkbox');
  checkboxes.prop('checked', $(this).is(':checked'));
});
Copy after login

Explanation:

  • The change event is bound to the "select_all" checkbox using the $('#select_all').change(...) selector.
  • When the checkbox is clicked or its state changes (i.e., checked or unchecked), the event handler function is executed.
  • The $(this).closest('form').find(':checkbox'); selector retrieves all checkbox elements within the same form as the "select_all" checkbox. This excludes the "select_all" checkbox since it is the initiator of the event.
  • The prop('checked', $(this).is(':checked')); line determines whether the "select_all" checkbox is checked or not. It then applies the same checked state to all other checkboxes in the form.

This approach effectively toggles the checked state of all checkboxes when the "select_all" checkbox is clicked.

The above is the detailed content of How to Select All Checkboxes Except for a Specific One with jQuery?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template