How to Change Selected Value of a Drop-Down List Using jQuery

Drop-down lists are a common form of web elements used for selection and data representation. They provide a way to present a list of options to the user to choose from.

At times, it is necessary to change the selected option dynamically, based on user interactions or other events.

In this tutorial, we’ll learn how to do so using jQuery.


jQuery

jQuery is a popular JavaScript library that makes it easier to manipulate HTML elements and perform tasks on the web page.

We’ll be using a few functions from jQuery to change the selected option in a drop-down list.

Changing the Selected Option

To change the selected option in a drop-down list, we need to modify the value of the “selected” attribute of the option element.

jQuery provides several methods to achieve this.

The first method is to use the “val()” function.

This function takes a value as an argument and sets the selected option to the one with a matching value.

$('#dropdown').val('Option 2');

In this example, the drop-down list with an id of “dropdown” will have its selected option changed to “Option 2”.

Another method is to use the “prop()” function to set the “selected” attribute to “true”.

$('#dropdown option[value="Option 2"]').prop('selected', true);

In this example, the option with a value of “Option 2” will have its “selected” attribute set to “true”, making it the selected option.


Conclusion

In this tutorial, we learned how to change the selected option in a drop-down list using jQuery.

Whether it’s based on user interactions or other events, it is possible to dynamically update the selected option.

By using the “val()” or “prop()” function, we can achieve this with just a few lines of code.

I hope you found this tutorial helpful.

If you have any questions or feedback, feel free to leave a comment below.