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:
<div id="div1">
<select id="select1">
<option value="car">Car</option>
<option value="bus" selected>Bus</option>
<option value="train">Train</option>
</select>
<div id="click-me" onclick="changeSelect()">Change select to first option</div>
</div>
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:
Full Code:
<div id="div1">
<select id="select1">
<option value="car">Car</option>
<option value="bus" slected>Bus</option>
<option value="train">Train</option>
</select>
<div id="click-me" onclick="changeSelect()">Change select to first option</div>
</div>
<script>
function changeSelect(){
$("#select1").val($("#select1 option:first").val());
};
</script>
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:
Full Code:
<div id="div1">
<select id="select2">
<option value="car">Car</option>
<option value="bus">Bus</option>
<option value="train">Train</option>
</select>
<div id="click-me" onclick="changeSelect2()">Change select to last option</div>
</div>
<script>
function changeSelect2(){
$("#select2").val($("#select2 option:last").val());
};
</script>
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:
Full Code:
<div id="div1">
<select id="select3">
<option value="car">Car</option>
<option value="bus">Bus</option>
<option value="train">Train</option>
</select>
<div id="click-me" onclick="changeSelect3()">Change select to middle option</div>
</div>
<script>
function changeSelect3(){
$("#select3").val($("#select3 option:nth-child(2)").val());
};
</script>
Hopefully this article has been useful to help you understand how to use jQuery to set select to the first option.
Leave a Reply