Jquery – Select first Option in Select element with jQuery

jqueryjquery-mobile

I've read a few posts on how to select the first Option in an HTML Select element with jQuery, but I can't seem to get it working on a jQuery mobile page.

Select element:

<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'm invoking to select first Option:

$("#myList").val($("#myList option:first").val());

I'm not trying to get the value of the first option in the select element, I'm actually trying to select it.

Is there something else I need to do in order to get this to work on a jQuery mobile page?

Thanks.

Best Solution

One solution is to use selectmenu("refresh").

refresh update the custom select: 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.

//refresh value         
$('select').selectmenu('refresh');

//refresh and force rebuild
$('select').selectmenu('refresh', true);

source

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");

fiddle