We can use jQuery to set select to the first option by using the jQuery val() method to set the value of the select element to the value of the first option.

$("#select-element").val($("#select-element option:first").val());

If using WordPress, don’t forget to change the $ to jQuery:

jQuery("#select-element").val(jQuery("#select-element option:first").val());

Let’s see an example of this below.


Lets say we have the following HTML:

Change select to first option

In this example, the selected option to start will be the middle option, Bus. We can put our code above to use to make it so that when the user clicks the button, the selected option will be changed to the first option, Car.

We will create a function that runs this code when the user clicks our button.

Here is the JavaScript code we will need:

function changeSelect(){
  $("#select1").val($("#select1 option:first").val());
}; 

Try it out below:

Code Output:

Change select to first option

Full Code:

Change select to first option

Using jQuery to Set Select to the Last Option

To set the Select to the last option, we can use our code from above, just change first to last.

$("#select-element").val($("#select-element option:last").val());

Let’s see this in action below:

Code Output:

Change select to last option

Full Code:

Change select to last option

Using jQuery to Set Select to a Specific Option

To set the Select to a specfic option, in this case the middle option, Bus, we can use the nth-child() selector.

$("#select-element").val($("#select-element option:nth-child(2)").val());

Let’s see this in action below:

Code Output:

Change select to middle option

Full Code:

Change select to middle option

Hopefully this article has been useful to help you understand how to use jQuery to set select to the first option.

Categorized in:

jQuery,

Last Update: March 11, 2024