jQuery API

:selected Selector

selected selector

version added: 1.0jQuery(':selected')

Description: Selects all elements that are selected.

The :selected selector works for <option> elements. It does not work for checkboxes or radio inputs; use :checked for them.

Example:

Attaches a change event to the select that gets the text for each selected option and writes them in the div. It then triggers the event for the initial text draw.

<!DOCTYPE html>
<html>
<head>
  <style>
  div { color:red; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
	<select name="garden" multiple="multiple">

    <option>Flowers</option>
    <option selected="selected">Shrubs</option>
    <option>Trees</option>
    <option selected="selected">Bushes</option>

    <option>Grass</option>
    <option>Dirt</option>
  </select>
  <div></div>
<script>

    $("select").change(function () {
          var str = "";
          $("select option:selected").each(function () {
                str += $(this).text() + " ";
              });
          $("div").text(str);
        })
        .trigger('change');
</script>
</body>
</html>

Demo:

Comments

  • Support requests, bug reports, and off-topic comments will be deleted without warning.

  • Please do post corrections or additional examples for :selected Selector below. We aim to quickly move corrections into the documentation.
  • If you need help, post at the forums or in the #jquery IRC channel.
  • Report bugs on the bug tracker or the jQuery Forum.
  • Discussions about the API specifically should be addressed in the Developing jQuery Core forum.
  • Ided
    How do you get the value versus the text?
  • Cdundee
    change $(this).text() to $(this).val()