jQuery set select value

Written by on April 25, 2010 in JavaScript - No comments

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.

About the Author

Greg Winiarski is a freelance PHP and JavaScript programmer. He specializes in web applications and WordPress development.

Leave a Comment