How To Dropdown Selected Value In Jquery

In this blog post, we will learn how to get the selected value from a dropdown list using jQuery. The <select> element is used to create a dropdown list in HTML forms. We will use the .val() method in jQuery to get the value of the selected option.

Step 1: Create an HTML Dropdown List

First, let’s create an HTML dropdown list with some options. We will use the <select> element and the <option> element for this purpose.

Here is an example of an HTML dropdown list:

    <select id="fruits">
        <option value="apple">Apple</option>
        <option value="banana">Banana</option>
        <option value="orange">Orange</option>
    </select>
    

Step 2: Include jQuery Library

Next, we need to include the jQuery library in our HTML file. You can either download the library and include it in your project, or you can use a CDN (Content Delivery Network) link to include it.

Here’s an example of including the jQuery library using a CDN link:

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    

Step 3: Get the Selected Value Using jQuery

Now that we have our HTML dropdown list and the jQuery library, let’s get the selected value using the .val() method.

Here’s an example of how to get the selected value from the dropdown list when the user changes the selection:

    <script>
        $(document).ready(function() {
            $("#fruits").change(function() {
                var selectedValue = $(this).val();
                alert("You have selected: " + selectedValue);
            });
        });
    </script>
    

In the example above, we first wait for the document to be ready using the $(document).ready() function. Then, we bind a change event to the dropdown list with the ID #fruits.

Inside the change event handler, we use the $(this).val() method to get the value of the currently selected option. Finally, we display an alert box with the selected value.

Conclusion

In this blog post, we learned how to get the selected value from a dropdown list using jQuery. By using the .val() method, you can easily retrieve the value of the selected option in a dropdown list and use it in your code as needed.