Home »
jQuery »
jQuery Examples
How to make the first option of <select> selected with jQuery?
Let's learn how can we select the first option of the given drop-down menu using jQuery?
Submitted by Pratishtha Saxena, on November 16, 2022
Consider a scenario, you are given a drop-down list with some options within. We need to make sure that the appropriate option gets selected which is dependent on some other event. For example, if the user is of age born in the year 2001, then the age from the drop-down gets selected depending on that. Now in order to select the appropriate option without actually selecting it, we need to use the jQuery prop() method.
The prop() method in jQuery helps to set or return the property of the selected element. When the property has to be returned, then the name of the property (attribute) is defined and it will return the value of the matched property value of the element. When the property has to be set, then along with the property name, property value is also to be given.
Syntax:
$('selector').prop('propertyName');
$('selector').prop('propertyName','value');
This method sets the attribute of all the matched elements and returns the property value of the first matched element.
Now, in order to select the first option of the select box, we will pass the selectedIndex property and 0 as its value (which represents the first element of any list).
The below given example shows how to implement this technique and returns the output when the button is clicked.
jQuery example to make the first option of <select> selected
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<title>Document</title>
</head>
<body>
<h2>Make First Option of Drop-Down Select Using jQuery</h2>
<p>Click the button to select the first option of the following drop-down.</p>
<button>Select</button>
<hr>
Drop-Down List :
<select>
<option>Day 1</option>
<option>Day 2</option>
<option>Day 3</option>
<option>Day 4</option>
</select>
<hr>
<h3></h3>
</body>
<script type="text/javascript">
$(document).ready(function(){
$('button').click(function(){
var selected = $('select').prop('selectedIndex',0).val();
$('h3').html('First Option is : ' + selected);
});
});
</script>
</html>
Output: