Select the first option in the Select element with jQuery
I've read several posts on how to select the first option in an HTML Select element using jQuery, but I can't seem to get it to work on the jQuery mobile page.
Select an item:
<select id="myList">
<option value="" selected>Select a List</option>
<option value="1">Item 1</option>
<option value="2">Item 2</option>
<option value="3">Item 3</option>
</select>
Script I am calling to select the first option:
$("#myList").val($("#myList option:first").val());
I am not trying to get the value of the first parameter in the select element, I am actually trying to select it.
Is there something else I need to do to get this to work on a jQuery mobile page?
Thank.
source to share
One solution is to use selectmenu("refresh")
.
update update the user's selection: . This is used to update a custom select to display the select's own value. If the number of options in the selection differs from the number of items in the custom menu, it will rebuild the custom menu. Also, if you pass the truth to the argument you can force the restore.
//refresh value
$('select').selectmenu('refresh');
//refresh and force rebuild
$('select').selectmenu('refresh', true);
Html
<select id="myList">
<option value="" selected>Select a List</option>
<option value="1">Item 1</option>
<option value="2">Item 2</option>
<option value="3">Item 3</option>
</select>
Js
$("#myList").val($("#myList option:eq(1)").val());
$("#myList").selectmenu("refresh");
source to share
To make the first option in the selected list use this:
$("#myList option:eq(0)").attr("selected","selected");
But in your case, I think the first option is selected by default, so if you meant parameter with value = "1", than use this:
$("#myList option:eq(1)").attr("selected","selected");
UPDATE:
If you have a parameter value, you can also use this:
$("#myList option[value='2']").attr("selected","selected");
source to share