• jQuery Video Tutorials

jQuery :checked Selector



The :checked selector in jQuery is used to select all checked or selected elements.

It applies to <input> elements of type "checkbox" or "radio", as well as <option> elements within a <select> dropdown.

Syntax

Following is the syntax of :checked selector in jQuery −

$(":checked")

Parameters

Following are the parameters of this method −

  • ":checked" − This selector selects all checked elements within the entire document.

Example 1

In the following example, we are using the ":checked" to select all the checked checkboxes −

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
          $(":checked").wrap("<span style='background-color:yellow'>")
        });
    </script>
</head>
<body>
    <h1>Select Your Interests</h1>
    <label><input type="checkbox" value="Music" checked> Music</label><br>
    <label><input type="checkbox" value="Sports"> Sports</label><br>
    <label><input type="checkbox" value="Reading"> Reading</label><br>
    <label><input type="checkbox" value="Traveling"> Traveling</label><br>
    <div id="result"></div>
</body>
</html>

When we execute the above program, the checked checkboxes will be selected and wrapped with a <span> element with a yellow background color.

Example 2

In this example, we are using the ":checked" to select all the checked radio buttons −

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
          $(":checked").wrap("<span style='background-color:yellow'>")
        });
    </script>
</head>
<body>
    <h1>Select Your Interests</h1>
    <label><input type="radio" value="Music" checked> Music</label><br>
    <label><input type="radio" value="Sports" checked> Sports</label><br>
    <label><input type="radio" value="Reading"> Reading</label><br>
    <label><input type="radio" value="Traveling"> Traveling</label><br>
    <div id="result"></div>
</body>
</html>

After executing the above program, the checked radio buttons will be selected and wrapped with a <span> element with a yellow background color.

jquery_ref_selectors.htm
Advertisements