jQuery – :selected Selector

The jQuery selected selector selects all elements that are selected. The :selected selector works for <option> elements. It does not work for checkboxes or radio buttons.

Source Code

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  
<select name="fruits" multiple="multiple">

    <option>Apple</option>
    <option selected="selected">Mango</option>
    <option>Banana</option>
    <option selected="selected">Pineapple</option>

    <option>Grapes</option>
 
</select>
<button>Click Here</button>
<div id="div1" style="color:red;"></div>
  
<script>
jQuery("button").click(function () {
	var str = "";
	jQuery("select option:selected").each(function () {
        str += jQuery(this).text() + " ";
      });
	jQuery("#div1").text(str + " selected");
});
</script>
</body>
</html>

Demo

Following example finds all selected item in an option element and displays them in a div.


,

No comments yet.

Leave a Reply