How To Option Value In Jquery

In this blog post, we will discuss how to get and set the value of an <option> element in a <select> dropdown list using jQuery. jQuery simplifies the process of working with HTML elements, and in this example, we’ll see how it can help us easily manipulate the selected options in a dropdown list. Let’s dive in!

Getting the Selected Option Value

To get the value of the selected option in a dropdown list, we can use the val() method provided by jQuery. The val() method, when called without any arguments, returns the value of the first selected option in the dropdown list.

Here’s an example:

    $(document).ready(function() {
        $('#mySelect').change(function() {
            var selectedValue = $(this).val();
            alert('Selected Value: ' + selectedValue);
        });
    });
    

In this example, we have an event handler that is triggered when the dropdown value changes. Inside the event handler, we use $(this).val() to get the value of the selected option and display it in an alert.

Setting the Selected Option Value

Now, let’s see how we can set the value of the selected option in a dropdown list. To do this, we can again use the val() method, but this time we’ll pass the desired value as an argument.

Here’s an example:

    $(document).ready(function() {
        $('#setOptionBtn').click(function() {
            var newValue = 'option2';
            $('#mySelect').val(newValue);
        });
    });
    

In this example, we have a button with the ID setOptionBtn that, when clicked, sets the value of the dropdown list to “option2”. We do this using the val() method with the desired value as an argument.

Conclusion

In this blog post, we have learned how to get and set the value of an <option> element in a <select> dropdown list using jQuery. We have seen how the val() method can be used to perform both tasks, making it easy to work with dropdown lists in your web applications. Happy coding!