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.

+3


source to share


3 answers


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

      

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

      

violin

+4


source


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

      

0


source


Please correct me if I don't get the problem correctly. If you just want to get the value of the selected option, you can just get it.

$("#myList").val();

      

Hope it helps ...

Happy learning :)

-1


source







All Articles