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');