Page Content

Tutorials

What are the :Selected Selector in jQuery With Example

:Selected Selector in jQuery

The :selected selection in jQuery works well with HTML form components, especially dropdown lists. It enables targeting and working with items in a menu. Describe it.

What is the Selector?

A custom jQuery selector that belongs to the form filter category is the :selected selector. Matching items that the user has selected within a dropdown list or multiple-selection box is its main purpose.

Syntax:

Like all jQuery selectors, :selected starts with $(selector) and the dollar symbol.action. Using the :selected selector has a simple basic syntax:

$(':selected')

All of the elements that are now selected within your HTML content will be selected using this simple approach. You can combine it with other selectors to get more focused targeting. To choose the chosen option within a element with a certain ID, for instance, you may use $(‘#yourSelectID option:selected’).

How it Works

The :selected selector streamlines more intricate JavaScript code that would otherwise be required to identify the selected item in a dropdown list. A thorough examination of its context and functionality is provided below:

Targeted Elements: In contrast to other form selectors such as :checked, which is applicable to checkboxes and radio buttons, :selected is only intended for elements in menus. Because of its specialisation, it is very effective at what it is meant to do.

Form Filter Category: Among jQuery’s many form filters are :input, :text, :password, :file, :radio, :checkbox, :submit, :image, :reset, :button, :enabled, and :disabled. Work with user input fields easier with this wide form picker set.

Dynamic State Detection: In response to user activity, the selection state of a element may change dynamically. These modifications can be detected by jQuery’s change() function. The change() event corresponds to a element’s value change. Validating or changing web pages in real time requires this functionality, such as ensuring a user writes the correct data in a text field depending on a selection.

Retrieving Values: After selecting an element with :selected, use.text() or.val() to retrieve its text or value.

jQuery Mobile Enhancements: jQuery Mobile makes select menus more user-friendly on touch devices with significant enhancements. jQuery Mobile may style the platform’s native select widget or create one. Custom-styled select menus have a number of advantages, such as adding new capabilities like multiple select support and restoring functions that are absent from native widgets (like optgroup support on Android). For several choices, jQuery Mobile offers:

  • Pop-up menu header close button.
  • Checkboxes adjacent to items show their selection status.
  • Upon selecting two or more items, a counter bubble appears in the select button.
  • Upon closing the pop-up, the text of the selected items is appended to the select button; if it is too long, it may be truncated.
  • To display long lists in a separate window for easier scrolling.
  • To make a tag unselectable, use the disabled property.
  • If set in the placeholder option, placeholder text may appear in the select button.

Code Example

This thorough code example shows how to use the :selected selector with both single-selection and multiple-selection dropdowns:

<!DOCTYPE html>
<html>
<head>
  <title>:selected Selector</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<h3>Favorite Fruit:</h3>
<select id="fruitSelector">
  <option value="">--Choose--</option>
  <option value="apple">Apple</option>
  <option value="banana" selected>Banana</option>
  <option value="orange">Orange</option>
</select>
<button id="getFruit">Get Fruit</button>
<p id="fruitResult"></p>
<h3>Favorite Vegetables:</h3>
<select id="vegSelector" multiple size="4">
  <option value="carrot" selected>Carrot</option>
  <option value="spinach" selected>Spinach</option>
  <option value="potato">Potato</option>
  <option value="tomato">Tomato</option>
</select>
<button id="getVeg">Get Vegetables</button>
<p id="vegResult"></p>
<script>
$(function() {
  $('#getFruit').click(function() {
    let opt = $('#fruitSelector option:selected');
    $('#fruitResult').text(opt.val() ? 'Fruit: ' + opt.text() : 'No fruit selected.');
  });
  $('#getVeg').click(function() {
    let result = [];
    $('#vegSelector option:selected').each(function() {
      result.push($(this).text());
    });
    $('#vegResult').html(result.length ? 'Vegetables: ' + result.join(', ') : 'No vegetables selected.');
  });
});
</script>
</body>
</html>

Output:

Favorite Fruit:

Apple       Get Fruit
Fruit: Apple
Favorite Vegetables:

Carrot
Spinach
Potato
Tomato            Get Vegetables
Vegetables: Potato

Explanation of the Code

$(document).ready(function() { … });: This pattern matters to jQuery. This means the browser loads and parses the complete DOM before running JavaScript code in this method. This blocks jQuery from accessing HTML items before the DOM.

$(“#getFruit”).click(function() { … });: This line gives the button an event handler with ID getFruit. Use click() to easily bind a function to the click event. This button launches the argument’s anonymous function.

var selectedOption = $(“#fruitSelector option:selected”);: Here’s when the :selected selector is useful.

  • $(“#fruitSelector”): In this section, the ID fruitSelector is used to target the selected element. ID selectors are extremely effective and one of the three primary selection types in jQuery, along with HTML tag-based and class-based selectors.
  • option:selected: The :selected filter is used in this important section. In this case, it instructs jQuery to search for any components that are currently marked as selected within the previously selected #fruitSelector element. There will usually only be one choice selected at a time because it is a single-selection dropdown.


if (selectedOption.val()) { … } else { … }: This conditional determines whether the option that has been picked is valid (that is, not the blank placeholder option). The value attribute of the selected element is retrieved using the.val() function. In particular,.val() is used to get and set content for form fields.

$(“#fruitResult”).html(“Fruit Selection: “+ selectedOption.text()” (Value: “+ selectedOption.val”):

  • Find the displayed text of the element (e.g. “Banana”) using the selectedOption.text() function.
  • When $(“#fruitResult”).html() and the ID fruitResult are used, the div element’s HTML content is set. Fruit value and content are dynamically updated on the website.

$(“#vegetableSelector option:selected”).each(function() { … });: :selected is demonstrated in this block using a multiple-selection dropdown.

  • This kind of dropdown allows for the selection of several options, therefore a direct.text() or.val() call on the entire selection will only yield the data for the first entry.
  • To loop over each element that matches the option:selected filter, use the.each() method. Every option that is selected causes the method inside.each() to be run.
  • The current DOM element being iterated over, or one of the chosen elements, is denoted by $(this) inside the each() function. Using $(this) to wrap this generates a jQuery object, which lets you utilise jQuery methods like.text() and.val() on that particular element.
  • SelectVegetables.push() pushes each vegetable’s value and text into an array.
  • chosenVegetables.join(“br>”): Finally, the vegetableResult div displays the chosenVegetables array concatenated into a single string using join(), separated by an HTML line break.

Conclusion

A strong and effective tool for working with dropdown elements in HTML forms is the :selected selection in jQuery. Whether from a single-selection or multi-selection list, it enables developers to quickly locate and work with items that are currently selected by the user. It is perfect for real-time updates, form validation, and dynamic user feedback because it streamlines activities that would normally need verbose JavaScript code when used as a form filter.

Kowsalya
Kowsalya
Hi, I'm Kowsalya a B.Com graduate and currently working as an Author at Govindhtech Solutions. I'm deeply passionate about publishing the latest tech news and tutorials that bringing insightful updates to readers. I enjoy creating step-by-step guides and making complex topics easier to understand for everyone.
Index