Page Content

Tutorials

How to Use :Checkbox Selector in jQuery With Code Example

:Checkbox Selector in jQuery

The jQuery :checkbox selector locates and modifies HTML form components. jQuery simplifies HTML page traversal, event handling, animation, and Ajax interactions, helping developers “write less, do more”. It adds form selectors to CSS-based selects to correctly target HTML components for modification.

What is the selector?

Only components with type=”checkbox” can be selected using jQuery’s form-specific filters, such as the :checkbox selector. Text boxes, buttons, and pick menus are just a few of the HTML form features that may be easily worked with this collection of filters.

Syntax:

Using the :checkbox selector has the following simple syntax:

($(':checkbox')

Like all jQuery selectors, it begins with $() and the dollar sign.

How it works

Using $(‘:checkbox’), jQuery looks for elements with the checkbox type attribute in the DOM. The function generates a jQuery object with zero or more matched DOM elements. Chaining other jQuery methods like.attr(),.prop(), or.click() to this object lets you interact with selected checkboxes in different ways.

Using jQuery selectors like :checkbox compensates for browser-dependent idiosyncrasies and adds functions that the basic DOM lacks. So, your code will work consistently in all officially supported browsers without having to develop separate code for each. This selection finds many checkboxes and creates an array or list for action.

If you want to set the checked property to true for every checkbox selected, jQuery will handle the DOM modification and ensure the change is valid and consistent across browsers. This JavaScript-based dynamic alteration of web page components is commonly known as Dynamic HTML (DHTML).

Code Example

<!DOCTYPE
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>jQuery Checkbox Example</title>
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
  <script type="text/javascript">
    $(document).ready(function () {
      $('form').submit(function (event) {
        event.preventDefault(); // Prevent actual form submission
        var selectedFruits = [];
        // Use :checkbox selector to get all checked checkboxes
        $('input:checkbox[name="fruit"]:checked').each(function () {
          selectedFruits.push($(this).val());
        });
        if (selectedFruits.length > 0) {
          $('#result').html('You selected: ' + selectedFruits.join(', '));
        } else {
          $('#result').html('You did not select any fruit.');
        }
      });
    });
  </script>
</head>
<body>
  <form action="" method="post">
    <p>Select your favorite fruits:</p>
    <input type="checkbox" id="fruit1" name="fruit" value="Apple"> <label for="fruit1">Apple</label><br />
    <input type="checkbox" id="fruit2" name="fruit" value="Banana"> <label for="fruit2">Banana</label><br />
    <input type="checkbox" id="fruit3" name="fruit" value="Orange"> <label for="fruit3">Orange</label><br />
    <input type="checkbox" id="fruit4" name="fruit" value="Grape"> <label for="fruit4">Grape</label><br />
    <br />
    <input type="submit" value="Submit" />
  </form>
  <div id="result" style="margin-top: 20px; font-weight: bold;"></div>
</body>
</html>

Output:

Select your favorite fruits:
 Apple
 Banana
 Orange
 Grape
Submit
You selected: Banana

Explanation of the code

<script type=”text/javascript” src=”js/jquery-1.4.min.js”></script>: jQuery is added to HTML by the line. Any jQuery code needs it.

$(document).ready(function(){ … });: This fundamental jQuery method only executes when the web page loads and the DOM is established. This avoids errors when working with unloaded things.

$(‘:checkbox’): The selector is showing here. Every element on the page with the type attribute checkbox is identified by it.

.attr({checked:’true’}): The selector is connected to a jQuery method called.attr({checked:’true’}). Setting or retrieving attribute values is done with the.attr() method. The checked attribute of all selected checkboxes is set to ‘true’ in this instance, making them show as checked in the browser. For Boolean properties, jQuery .prop() function is frequently chosen for more straightforward manipulation (.prop(‘checked’, true)), even if ‘true’ is used as a string for the property value above.

All of the fruit checkboxes will be pre-checked when you view this HTML file in a web browser because the jQuery function is run after the page loaded. This illustrates the quick and consistent manipulation of particular form components throughout a web page made possible by the :checkbox selector in conjunction with other jQuery capabilities.

Conclusion

The :checkbox selector in jQuery simplifies picking all HTML elements with a “checkbox” type property. This makes it easy to enable/disable checkbox groups, style them, or iterate through them to collect selected values. This may be done concisely with $( “:checkbox” ), a jQuery extension. In current web development, especially with many components, the native CSS attribute selector, $( “input[type=’checkbox’]” ), directly uses the browser’s highly optimised querySelectorAll() technique for best efficiency. Regardless of syntax, jQuery’s :checkbox feature (typically paired with the :checked pseudo-class to indicate selected options) is essential for managing interactive form components.

Kowsalya
Kowsalya
Hi, I'm Kowsalya a B.Com graduate and currently working as an Author at Govindhtech Solutions. I'm deeply passionate about publishing the latest tech news and tutorials that bringing insightful updates to readers. I enjoy creating step-by-step guides and making complex topics easier to understand for everyone.
Index