• jQuery Video Tutorials

jQuery :selected Selector



The :selected selector in jQuery is used to select <option> elements that are currently selected within a <select> element.

We cannot use this selector for checkboxes or radio buttons. Instead, we need to use the :checked selector.

Syntax

Following is the syntax of :selected selector in jQuery −

$(":selected")

Parameters

Following are the parameters of this method −

  • ":selected" − This selector filters the selected <option> elements within the specified <select> element.

Example 1

In the following example, we are demonstrating the basic usage of :seleted selector in jQuery −

<html>
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
        $(":selected").css("background-color", "green")
    });
  </script>
</head>
<body>
  <select>
    <option value="1">Option 1</option>
    <option value="2" selected>Option 2</option>
    <option value="3">Option 3</option>
  </select>
</body>
</html>

When we execute the above program, :selector selects the option element ("Option 2) that is pre-selected.

Example 2

In this example, we are pre-selecting multiple dropdown options −

<html>
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $("button").click(function(){
        var selectedOptions = [];
        $(":selected").each(function(){
          selectedOptions.push($(this).text());
        });
        alert("Selected options: " + selectedOptions.join(", "));
      });
    });
  </script>
</head>
<body>
  <select id="multiSelect" multiple>
    <option value="1">Option 1</option>
    <option value="2" selected>Option 2</option>
    <option value="3" selected>Option 3</option>
    <option value="4">Option 4</option>
  </select>
  <button>Get Selected Values</button>
</body>
</html>

After executing the program, an alert box displays the text of all selected options, separated by commas.

jquery_ref_selectors.htm
Advertisements