📜  $(this) option selected jquery - Javascript (1)

📅  最后修改于: 2023-12-03 15:29:05.813000             🧑  作者: Mango

$(this) option selected in jQuery

In jQuery, $(this) option:selected is a selector that refers to a selected option element within a select element. It can be used to retrieve the value of the selected option or to perform actions based on the selected option.

Retrieving the value of the selected option

To retrieve the value of the selected option element, you can use the following code:

$(document).ready(function() {
   $("#mySelect").change(function() {
      var selectedOption = $(this).find("option:selected").val();
      console.log("Selected option: " + selectedOption);
   });
});

In this code, $("#mySelect") selects the select element with the id of mySelect. The .change() method adds an event listener that triggers when the select element is changed. $(this) refers to the select element that triggered the event. The .find("option:selected") selector finds the selected option element within the select element, and the .val() method retrieves the value of the selected option.

Performing actions based on the selected option

You can also use $(this) option:selected to perform actions based on the selected option. For example, if you have a select element with options for different colors, you could use the following code to change the background color of the page based on the selected option:

$(document).ready(function() {
   $("#colorSelect").change(function() {
      var selectedOption = $(this).find("option:selected").val();
      $("body").css("background-color", selectedOption);
   });
});

In this code, $("#colorSelect") selects the select element with the id of colorSelect. The .change() method adds an event listener that triggers when the select element is changed. $(this) refers to the select element that triggered the event. The .find("option:selected") selector finds the selected option element within the select element, and the .val() method retrieves the value of the selected option. Finally, $("body").css("background-color", selectedOption) changes the background color of the body element to the selected color.

Overall, $(this) option:selected is a useful selector in jQuery for working with selected option elements within select elements.