93 of 119 menu

Selector selected

The :selected selector selects elements that are selected, that is, those that have the selected attribute. The :selected selector works for elements with the option tag. It doesn't work with checkboxes (checkbox) or radio buttons (radio), for them use the checked selector. Since :selected is not part of the CSS spec, for better performance in modern browsers it's better to first filter elements using a pure css selector and then apply .filter(':selected').

Syntax

This is how we select elements with the selected attribute:

$(':selected');

Example

Let's make each item in the drop-down list appear below the list in green each time you select it. As you can see, the default items will be displayed before your first click, which are 'bbb' and 'ddd':

<select name="texts" multiple="multiple"> <option>aaa</option> <option selected="selected">bbb</option> <option>ccc</option> <option selected="selected">ddd</option> <option>eee</option> <option>fff</option> </select> <div></div> div { color: green; } $('select') .change(function() { let str = ''; $('select option:selected').each(function() { str += $(this).text() + ' '; }); $('div').text(str); }).trigger('change');

See also

  • method filter,
    which filters elements in a set by a given selector
  • attribute selected
  • selector checked,
    which selects elements that are selected, i.e. those that have the checked attribute
    or selected
  • tags option
    and select
byenru