JQuery Selected Selector Example

This tutorial explains usage of selected selector in jQuery. The selected selector event occurs when an element is selected in the document. It matches the elements that are of type selected in a page. It works for option elements that are pre-selected. The pre-selected option will be displayed first in the drop down list. The selected selector works for only option elements; it does not work for checkbox and radio box; use checked selector instead for them instead of using selected selector.

JQuery Selected Selector Syntax

$(“: selected”)

JQuery Selected Selector Example

<!doctype html>
<title>JQuery Selected Selector</title>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<h2>JQuery Selected Selector Example</h2>
<script type="text/javascript">
          $("div").text($("select option:selected").val()+ " is selected");
      <option value="bangalore">Bangalore</option>
      <option value="belgaum" selected="selected">Belgaum</option>
      <option value="hubli">Hubli</option>
      <option value="mangalore">Mangalore</option>
      <option value="gulbarga">Gulbarga</option>
  • As shown in the above program, we have used the code inside $(document).ready which is an event which fires up when document is ready. It will run once the page document object model is ready for JavaScript code to execute.
  • $(“:selected”).css(“background-color”,”red”); line defines selected selector which select the element that is pre-selected. The pre-selected element will display with red color background in the drop down list.
  • $(“div”).text($(“select option:selected”).val()+ ” is selected”); line defines the value of selected element by using val() method. The val() method returns value of attribute of the matched element in the document.
  • When we run the above script, we will get drop down list with list of options. The pre-selected element will display with red color background and when we select different element every time, the selected element will get display with green color.

JQuery Selected Selector Demo

When you run the above example, you would get the following output:

JQuery Selected Selector Example

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Share This

Share this post with your friends!