Changing a select element option using JavaScript.

This is a short JavaScript tutorial on how to change the selected option of a select HTML element. In this post, I will show you how to do it with and without JQuery.

Changing a select option without JQuery.

In this example, I am going to use vanilla JavaScript. Although the JQuery library is great, you may find yourself in situations where you don’t have access to it. It’s also not a terrific idea to include an entire library just for the sake of changing a select element.

Take a look at the custom JavaScript function that I wrote:

The JavaScript function above takes in two parameters. The unique ID of our select element and the value that we want to select. Inside our function, we loop through each option in the select element. If the value of the option matches the value that we want to select, we change the selectedIndex of the element and break out of the for loop.

An example of this function being used with a dropdown containing a list of country names:

In the example above, I used our custom function to select Ireland.

Changing a select option using JQuery.

If you’re already using the JavaScript JQuery library, then you can do something like this:

In the JQuery code above, we changed our select element option to “Ireland” using the attr method. However, you can also use the prop method:

In some cases, your value attributes might differ from the text of each option.

An example:

This is a common when you are dealing with select elements that were populated from a database or an array. In this scenario, you can use the following JQuery snippet:

In the code above, we changed our select element by using the val method. We set it to 3 because the Ireland option in our list has a value attribute of 3.

And that’s it! Hopefully, the above examples solved your problem!

Facebook Comments