'Fetch selected item of DropDownList using $(this) object

How do I fetch the selected item of a DropDownList using $(this)?

I have two DropDownLists in a web page. I want to get the selected item name. I tried 3 ways and each gave different result.

  1. This method showed the selected-item in "1st list" and also the selected-item of "2nd list". I guess this is because selector was not qualified with the ID.

  2. This method gave proper result. Can I achieve the same result using $(this), instead of ID. I guess the THIS object will be pointing to html-element.

  3. This method gave no results

    $(document).ready(
         function()
         {
              $('#IdServerType').bind("change", LoadX);
         }
    );
    

.

function LoadX()
{
    var str = "";
    
    /////  1
    str = $("select option:selected").text(); 
    console.log('menu clicked: ' + str);

    /////  2
    str = $("#IdServerType option:selected").text();
    console.log('menu clicked: ' + str);

    /////  3
    str = $("this option:selected").text(); //3
    console.log('menu clicked: ' + str);
}

Please note I want to keep the event registration and event-handler separate; helps in code maintenance.



Solution 1:[1]

You can use $(this) with children() to get the selected option element.

str = $(this).children("option:selected").text();

children('option:selected') will select the selected option from the select element.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1