Reputation: 26648
I have the following html:
<select id="id_visit_number" name="visit_number">
<option value="" selected="selected">---------</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
</select>
When the page is opened / loaded, I want the default option to be selected as Two
. So I tried the code below, but was not working
<script type='text/javascript">
$( document ).ready(function() {
$("select #id_visit_number option").filter(function() {
return $(this).val() == "2";
}).prop('selected', true);
});
</script>
How do I make an option selected by default when the page loads?
Upvotes: 1
Views: 15091
Reputation: 24638
Since IDs are supposed to be unique, you can always just write the ID without prefixing it with the element name and $(this).val() == "2"
can also be written as this.value == "2"
$("#id_visit_number option").filter(function() {
return this.value == "2";
}).prop('selected', true);
Please note that ("select #id_visit_number option")
is equivalent to:
$("select").find("#id_visit_number").find("option");
//clearly, that's not what you wanted.
Upvotes: 0
Reputation: 15393
No need to give space. because that id in select dropdownlist
change
$("select #id_visit_number option")
to
$("select#id_visit_number option")
Upvotes: 3