jQuery :checkbox Selector



The ":checkbox" selector in jQuery is used to select all the input elements with type = checkbox".

Checkboxes are a form input elements that provides users with multiple options to select them. These checkboxes can be either checked or unchecked.

Syntax

Following is the syntax of :checkbox selector in jQuery −

$(":checkbox")

Parameters

Following is the description of above syntax:

  • ":checkbox" − This selector will select all checkbox button elements in the document.

Example 1

In the following example, we are using the ":checkbox" selector to select all the <input> elements with type = "checkbox"

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            $('button').click(function() {
                $(':checkbox').wrap("<span style='background-color:yellow'>");
            });
        });
    </script>
</head>
<body>
    <form>
        <input type="text" name="username" placeholder="Enter text here"><br>
        Cricket: <input type="checkbox"><br>
        Badminton: <input type="checkbox"><br>
        Football: <input type="checkbox"><br>
        <button>Click</button>
    </form>
</body>
</html>

After executing and clicking the button, It selects all input elements with type=checkbox and wraps with a span element with yellow background color.

Example 2

In this example, we are disabling all the checkbox buttons in a form −

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            $("button").click(function() {
                $(":checkbox").prop("disabled", true);
            });
        });
    </script>
</head>
<body>
    <form>
        <label>
            <input type="checkbox" name="option" value="1"> Cricket
        </label>
        <label>
            <input type="checkbox" name="option" value="2"> Badminton
        </label>
        <label>
            <input type="checkbox" name="option" value="3"> Cricket
        </label>
        <br>
        <button>Disable All Checkboxes</button>
    </form>
</body>
</html>

After clicking the "Disable All Checkboxes", it selects all the input elements with type=checkbox and disables them.

jquery_ref_selectors.htm
Advertisements