


Manage the 'Select All/No Select All' checkbox functionality in a standalone container using jQuery
Jul 25, 2025 pm 07:51 PMCore Requirements and HTML Structure Design
In web development, we often encounter the need to provide a "Select All" feature in a set of check boxes so that users can quickly select or uncheck all relevant options. When there are multiple independent sets of checkboxes on the page, for example, in different categories or regions, each group needs to have its own "select all" function and cannot influence each other.
To achieve this, the key is to design a reasonable HTML structure and use jQuery's selector and DOM traversal methods to define the operating range.
The recommended HTML structure is as follows:
<div class="actions" id="actions" title="Actions"> <!-- First group of check boxes--> <div class="myDiv"> <div> <input type="checkbox" name="action" class="selectAll" value="0"> Select All</div> <br> <div> <input type="checkbox" name="action" value="1"> Item 1</div> <br> <div> <input type="checkbox" name="action" value="2"> Item 2</div> <br> <div> <input type="checkbox" name="action" value="3"> Item 3</div> <br> </div> <!-- Second group of check boxes--> <div class="myDiv"> <div> <input type="checkbox" name="action" class="selectAll" value="26">Select All</div> <br> <div> <input type="checkbox" name="action" value="27"> Item A</div> <br> <div> <input type="checkbox" name="action" value="28"> Item B</div> <br> <div> <input type="checkbox" name="action" value="29"> Item C</div> <br> <div> <input type="checkbox" name="action" value="30"> Item D</div> <br> <div> <input type="checkbox" name="action" value="31"> Item E</div> </div> </div>
Structural points:
- myDiv class: Each independent checkbox group is wrapped in a div element with the myDiv class. This class name is key, which allows us to easily locate specific checkbox groups via jQuery.
- selectAll class: The "Select All" check box in each group should add the selectAll class. This allows us to accurately select and listen to these special check boxes.
- name attribute: Although the name attributes of all check boxes in this example are actions, in actual applications, in order to better semantic and form submission, different name attributes can be set for different groups of check boxes, but this does not affect the "select all" logic in this tutorial, because we operate based on the DOM structure.
jQuery implementation logic
We will implement the "Select All/No Select All" function through two main event listeners: one is used to handle the click event of the "Select All" check box, and the other is used to handle the click event of other ordinary check boxes in the group.
1. Control the click event of the "Select All" check box
When a user clicks on a "Select All" check box, we need to check or uncheck all other check boxes in the same group based on its current selected status.
$('.selectAll').on('click', function() { // Get the selected status of the current "Select All" check box let isSelected = $(this).is(':checked'); // Find the nearest parent .myDiv element to which the current "Select All" checkbox belongs // Then find all input elements of type checkbox in that parent $(this).parents('.myDiv').find('input[type="checkbox"]').each(function() { // Set the selected status of all found check boxes to be consistent with the "Select All" check box $(this).prop('checked', isSelected); }); });
Code parsing:
- $('.selectAll').on('click', function() { ... });: Listen to all click events for check boxes with selectAll class.
- let isSelected = $(this).is(':checked');: Gets the selected status (true or false) of the currently clicked "Select All" check box.
- $(this).parents('.myDiv'): This is a key step. It traverses the DOM tree upwards and finds the most recent parent element with the myDiv class that is currently clicked. This ensures that the operation is limited to the group to which the current check box belongs.
- .find('input[type="checkbox"]'): Inside the found .myDiv element, find all input elements of type checkbox.
- .each(function() { ... });: Iterate over these found check boxes.
- $(this).prop('checked', isSelected);: Use the prop() method to set the checked property of each check box. prop() is the recommended way to manipulate element properties, especially for Boolean properties.
2. Control the linkage of independent check boxes
When the user clicks any non-select all check box in the group, we need to decide whether to check or uncheck the "select all" check box in the group based on the selection of all check boxes in the same group.
$('input:not(".selectAll")').on('click', function() { // Get the nearest parent to which the check box is currently clicked belongs.myDiv element let $parentDiv = $(this).parents('.myDiv'); // Get the DOM element of the "Select All" check box in the group let selectAllCheckbox = $parentDiv.find('.selectAll')[0]; // Get the number of all non-Select All check boxes in the group let totalIndividualInputs = $parentDiv.find('input:not(".selectAll")').length; // Get the number of all selected non-Select All check boxes in the group let checkedIndividualInputs = $parentDiv.find('input:checked:not(".selectAll")').length; // Logical judgment: // 1. If the "Select All" check box is currently selected, but any independent check box is unchecked, cancel "Select All". if (selectAllCheckbox.checked && checkedIndividualInputs <p> <strong>Code parsing:</strong></p>
- $('input:not(".selectAll")').on('click', function() { ... });: Listen to all click events that are not the input type check box of the selectAll class.
- let $parentDiv = $(this).parents('.myDiv');: Similarly, find the .myDiv parent element to which the current click check box belongs to limit the operation range.
- let selectAllCheckbox = $parentDiv.find('.selectAll')[0];: Find the DOM element of the "Select All" check box in the current group. Note that [0] is to obtain the native DOM element, because the checked attribute is a native DOM attribute.
- totalIndividualInputs and checkedIndividualInputs: Calculate the total number of non-Select All check boxes in the group and the number of selected check boxes, respectively.
- Conditional judgment:
- The first if condition: If the "Select All" check box is selected (selectAllCheckbox.checked), but the number of independent check boxes actually selected is less than the total (checkedIndividualInputs
- The second else if condition: If all independent check boxes are selected (totalIndividualInputs === checkedIndividualInputs), the "Select All" check box is automatically selected.
Complete sample code
Combine the above HTML structure and jQuery code and introduce the jQuery library into the page to achieve the required functions.
<meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>jQuery Multiple Groups Select All Check Box</title> <!-- Introducing jQuery library--> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <style> .myDiv { border: 1px solid #ccc; padding: 10px; margin-bottom: 15px; background-color: #f9f9f9; } .myDiv div { margin-bottom: 5px; } </style> <div class="actions" id="actions" title="Actions"> <div class="myDiv"> <div> <input type="checkbox" name="action" class="selectAll" value="0"> **Select All Actions**</div> <br> <div> <input type="checkbox" name="action" value="1"> View Profile</div> <br> <div> <input type="checkbox" name="action" value="2"> Edit Settings</div> <br> <div> <input type="checkbox" name="action" value="3"> Delete Account</div> <br> </div> <div class="myDiv"> <div> <input type="checkbox" name="action" class="selectAll" value="26">**Select All Permissions**</div> <br> <div> <input type="checkbox" name="action" value="27"> Read Access</div> <br> <div> <input type="checkbox" name="action" value="28"> Write Access</div> <br> <div> <input type="checkbox" name="action" value="29"> Execute Access</div> <br> <div> <input type="checkbox" name="action" value="30"> Admin Rights</div> <br> <div> <input type="checkbox" name="action" value="31"> Audit Logs</div> </div> </div> <script> $(document).ready(function() { // Click event $('.selectAll').on('click', function() { let isSelected = $(this).is(':checked'); $(this).parents('.myDiv').find('input[type="checkbox"]').prop('checked', isSelected); }); // Click event $('input:not(".selectAll")').on('click', function() { let $parentDiv = $(this).parents('.myDiv'); let selectAllCheckbox = $parentDiv.find('.selectAll')[0]; let totalIndividualInputs = $parentDiv.find('input:not(".selectAll")').length; let checkedIndividualInputs = $parentDiv.find('input:checked:not(".selectAll")').length; // If the selection is checked, but some children are unchecked, unselect all if (selectAllCheckbox.checked && checkedIndividualInputs < totalIndividualInputs) { selectAllCheckbox.checked = false; } // If all children are checked, check Select All else if (totalIndividualInputs === checkedIndividualInputs) { selectAllCheckbox.checked = true; } }); }); </script>
Notes and best practices
- Reasonable use of class names and IDs: In this tutorial, we used class names (myDiv, selectAll) instead of IDs to identify elements, because class names can be applied to multiple elements, which is very suitable for scenarios where multiple sets of "Select All" check boxes are available. The ID should be unique.
- jQuery selector efficiency: The combination of parents('.myDiv').find(...) is efficient, which first looks upward to the nearest specific parent element and then downward to the child element, limiting the search scope to the current group, avoiding unnecessary global DOM traversal.
- prop() and attr(): For boolean properties (such as checked, selected, disabled), it is recommended to use the prop() method to set or get their values instead of attr(). prop() more accurately reflects the current state of the DOM element.
- Native DOM attribute access: In selectAllCheckbox.checked = false; or selectAllCheckbox.checked = true;, we directly access the checked property of the native DOM element. This is because $(element)[0] can get the first native DOM element wrapped by the jQuery object. For the reading and writing of simple attributes, it is usually more concise to directly operate the native DOM attributes.
- Code readability: Using meaningful variable names (such as isSelected, $parentDiv) and appropriate annotations can greatly improve the readability and maintenance of the code.
- Error handling/boundary situation: For this function, the above code has covered common usage scenarios. But in more complex applications, you may need to consider dynamic addition/removal checkboxes, at which point you may need to rebind events or use event delegates.
Summarize
Through the above method, we successfully implemented the function of managing the "Select All/No Select All" check box in multiple independent containers using jQuery. The core is to define the boundaries of the group through a clear HTML structure, and combine jQuery's powerful DOM traversal and event processing capabilities to accurately define the operating range within each independent check box group, thereby achieving independent control without interference. This pattern is very practical when building complex forms or data filtering interfaces.
The above is the detailed content of Manage the 'Select All/No Select All' checkbox functionality in a standalone container using jQuery. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Web development design is a promising career field. However, this industry also faces many challenges. As more businesses and brands turn to the online marketplace, web developers have the opportunity to demonstrate their skills and succeed in their careers. However, as demand for web development continues to grow, the number of developers is also increasing, resulting in increasingly fierce competition. But it’s exciting that if you have the talent and will, you can always find new ways to create unique designs and ideas. As a web developer, you may need to keep looking for new tools and resources. These new tools and resources not only make your job more convenient, but also improve the quality of your work, thus helping you win more business and customers. The trends of web development are constantly changing.

Do you want to connect your website to Yandex Webmaster Tools? Webmaster tools such as Google Search Console, Bing and Yandex can help you optimize your website, monitor traffic, manage robots.txt, check for website errors, and more. In this article, we will share how to add your WordPress website to the Yandex Webmaster Tool to monitor your search engine traffic. What is Yandex? Yandex is a popular search engine based in Russia, similar to Google and Bing. You can excel in Yandex

Do you need to fix HTTP image upload errors in WordPress? This error can be particularly frustrating when you create content in WordPress. This usually happens when you upload images or other files to your CMS using the built-in WordPress media library. In this article, we will show you how to easily fix HTTP image upload errors in WordPress. What is the reason for HTTP errors during WordPress media uploading? When you try to upload files to Wo using WordPress media uploader

Integrating Sentry and Bugsnag in Laravel can improve application stability and performance. 1. Add SentrySDK in composer.json. 2. Add Sentry service provider in config/app.php. 3. Configure SentryDSN in the .env file. 4. Add Sentry error report in App\Exceptions\Handler.php. 5. Use Sentry to catch and report exceptions and add additional context information. 6. Add Bugsnag error report in App\Exceptions\Handler.php. 7. Use Bugsnag monitoring

The methods to correctly handle this pointing in JavaScript closures include: 1. Use arrow functions, 2. Use bind methods, 3. Use variables to save this. These methods ensure that this intrinsic function correctly points to the context of the external function.

Understanding Nginx's configuration file path and initial settings is very important because it is the first step in optimizing and managing a web server. 1) The configuration file path is usually /etc/nginx/nginx.conf. The syntax can be found and tested using the nginx-t command. 2) The initial settings include global settings (such as user, worker_processes) and HTTP settings (such as include, log_format). These settings allow customization and extension according to requirements. Incorrect configuration may lead to performance issues and security vulnerabilities.

Strings in Python are immutable sequence types. 1) You can use single quotes, double quotes, triple quotes or str() functions to create strings. 2) The operation string can be done by splicing, formatting, searching, replacing and slicing. 3) Pay attention to immutability and encoding issues when processing strings. 4) Performance optimization can be performed using the join method instead of frequent splicing. 5) It is recommended to keep the code readable and use regular expressions to simplify complex operations.

The easiest way to calculate list length in Python is to use the len() function. 1) The len() function is suitable for lists, strings, tuples, dictionaries, etc., and returns the number of elements. 2) Although custom length calculation function is feasible, it is inefficient and is not recommended to use it in practical applications. 3) When processing large data sets, you can first calculate the length to avoid repeated calculations and improve performance. Using the len() function is simple, fast and reliable, and is the best practice for calculating list lengths.
