Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select dropdown option by value using jQuery

I have select following html structure

<select id="mainMenu" data-mini="true" name="select-choice-min">
   <option value="1">1</option>
   <option value="2">2</option>
   <option value="3">3</option>
   <option value="4">4</option>
   <option value="5">5</option>
   <option value="6">6</option>   
</select>

on page load I want initially set option with value 5 so I tried (but nothing changed)

$(document).ready(function () {
   $('#mainMenu option').eq(5).prop('selected', true);
})

I'm using jQuery 1.8.3 and jQuery mobile since this is mobile website

<script src="/Scripts/jquery-1.8.3.js"></script>
<script src="/Scripts/jquery.mobile-1.4.2.js"></script>

UPDATE:

I just realize that every code from posted answers works (as well as mine), #mainMenu option value is set to desired value (5) but it's text doesn't change (in any of this scenarios). Is this normal and is there workaround for this.

I tried $("mainMenu").text("5");

like image 921
user1765862 Avatar asked Sep 01 '25 03:09

user1765862


2 Answers

Refresh

This is used to update the custom select to reflect the native select element's value.If the number of options in the select are different than the number of items in the custom menu, it'll rebuild the custom menu. Also, if you pass a true argument you can force the rebuild to happen.

$("#mainMenu").val("5");
$("#mainMenu").selectmenu('refresh', true);

Take a look here Select menus

fiddle

like image 167
Alex Char Avatar answered Sep 02 '25 16:09

Alex Char


This is working fine:

$(document).ready(function () {
   $('#mainMenu option').eq(5).prop('selected', true);
})

Check JSFiddle Demo

But .eq(5) is index and start from 0 so if you want to select value=5, use .eq(4).

Also you can use this:

$("#mainMenu").val("5");

and also you can set the 5 as default selected value in your HTML code manually like this:

<option value="5" selected>5</option>
like image 36
Moshtaf Avatar answered Sep 02 '25 17:09

Moshtaf