I still sometimes forget how to set <select> value, although it’s pretty simple. I had to “figure it out again” today so here is a quick post for future reference for me and you if you are looking for such solution.
First let’s assume there is such “select” inside “form”.
<select id="my_select" name="fruits">
<option value="1">apple</option>
<option value="2">orange</option>
<option value="3">peach</option>
</select>Now in order to set option 2 (orange) as selected on DOM ready we can execute such short snippet of code
<script type="text/javascript"> $(function() { $("#my_select").val(2); }); </script>
What if <option> does not have “value” attribute? What then? That’s a homework assignment … ok i admit, i don’t know that, but on the other hand i never had to deal with select box that does not have this attribute set.
