
- jQuery - Home
- jQuery - Roadmap
- jQuery - Overview
- jQuery - Basics
- jQuery - Syntax
- jQuery - Selectors
- jQuery - Events
- jQuery - Attributes
- jQuery - AJAX
- jQuery CSS Manipulation
- jQuery - CSS Classes
- jQuery - Dimensions
- jQuery - CSS Properties
- jQuery Traversing
- jQuery - Traversing
- jQuery - Traversing Ancestors
- jQuery - Traversing Descendants
- jQuery References
- jQuery - Selectors
- jQuery - Events
- jQuery - Effects
- jQuery - HTML/CSS
- jQuery - Traversing
- jQuery - Miscellaneous
- jQuery - Properties
- jQuery - Utilities
- jQuery Plugins
- jQuery - Plugins
- jQuery - PagePiling.js
- jQuery - Flickerplate.js
- jQuery - Multiscroll.js
- jQuery - Slidebar.js
- jQuery - Rowgrid.js
- jQuery - Alertify.js
- jQuery - Progressbar.js
- jQuery - Slideshow.js
- jQuery - Drawsvg.js
- jQuery - Tagsort.js
- jQuery - LogosDistort.js
- jQuery - Filer.js
- jQuery - Whatsnearby.js
- jQuery - Checkout.js
- jQuery - Blockrain.js
- jQuery - Producttour.js
- jQuery - Megadropdown.js
- jQuery - Weather.js
jQuery :selected Selector
The :selected selector in jQuery is used to select <option> elements that are currently selected within a <select> element.
We cannot use this selector for checkboxes or radio buttons. Instead, we need to use the :checked selector.
Syntax
Following is the syntax of :selected selector in jQuery −
$(":selected")
Parameters
Following are the parameters of this method −
- ":selected" − This selector filters the selected <option> elements within the specified <select> element.
Example 1
In the following example, we are demonstrating the basic usage of :seleted selector in jQuery −
<html> <head> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function(){ $(":selected").css("background-color", "green") }); </script> </head> <body> <select> <option value="1">Option 1</option> <option value="2" selected>Option 2</option> <option value="3">Option 3</option> </select> </body> </html>
When we execute the above program, :selector selects the option element ("Option 2) that is pre-selected.
Example 2
In this example, we are pre-selecting multiple dropdown options −
<html> <head> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ var selectedOptions = []; $(":selected").each(function(){ selectedOptions.push($(this).text()); }); alert("Selected options: " + selectedOptions.join(", ")); }); }); </script> </head> <body> <select id="multiSelect" multiple> <option value="1">Option 1</option> <option value="2" selected>Option 2</option> <option value="3" selected>Option 3</option> <option value="4">Option 4</option> </select> <button>Get Selected Values</button> </body> </html>
After executing the program, an alert box displays the text of all selected options, separated by commas.
jquery_ref_selectors.htm
Advertisements