JQuery Get Selected Dropdown Value on Change Event

This is a common scenario in web development when you want to capture the user's selection from a dropdown list.

To retrieve the selected dropdown value on change event in jQuery, bind a function to the dropdown's change event. Inside the function, use $(this).val() to get the selected value.

Example:

$('#dropdown').change(function() { var selectedValue = $(this).val(); console.log(selectedValue); });
run this source code Browser View

Here's a step-by-step breakdown with examples:

HTML Structure

First, you need an HTML dropdown element.

<select id="myDropdown"> <option value="option1">Option 1</option> <option value="option2">Option 2</option> <option value="option3">Option 3</option> </select> <p id="result"></p>

jQuery Event Handling

Use jQuery to handle the change event of the dropdown. The change event is triggered when the selected option changes.

$(document).ready(function() { $("#myDropdown").change(function() { var selectedValue = $(this).val(); // Get the selected value $("#result").text("Selected Value: " + selectedValue); // Display the selected value }); });

In this example, when the user selects an option from the dropdown, the change event is triggered. The code within the change event handler fetches the selected value using $(this).val() and then updates the content of the <p> element with the ID "result" to display the selected value.

Let's say the user selects "Option 2" from the dropdown. The result will be:

Selected Value: option2

This way, you're able to capture the selected value of the dropdown using jQuery's change event and perform actions based on the user's choice.

Full Source | jQuery

<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script> <script> $(document).ready(function() { $("#myDropdown1").change(function() { var selectedValue = $(this).val(); // Get the selected value $("#result").text("Selected Value: " + selectedValue); // Display the selected value }); }); </script> </head> <body> <select id="myDropdown1"> <option value="option1">Option 1</option> <option value="option2">Option 2</option> <option value="option3">Option 3</option> </select> <p id="result"></p> </body> </html>

Conclusion

To retrieve the selected value from a dropdown using jQuery's change event, you bind the event to the dropdown element. Upon selection change, the event handler captures the chosen value using $(this).val() and allows you to perform actions based on the user's selection. This technique provides an interactive way to obtain and respond to user choices in dropdown menus.