jQuery: Set the default selected OPTION of a HTML SELECT list

Setting the default selected option dynamically with PHP was going to take too long so I decided to use jQuery instead. After some playing around it was an easy operation.

Setting the default selected option in jQuery is simple. Take, for example the select list below:

1
2
3
4
5
6
7
8
<select class="country_list" name="country_selected">
                    <option value="GB" class="gb">United Kingdom</option>
                    <option value="IN" class="in">International</option>
                    <option value="AU" class="au">Australia</option>
                    <option value="AT" class="at">Austria</option>
                    <option value="BE" class="be">Belgium</option>
                    <option value="BR" class="br">Brazil</option>
</select>

To set the country you reference the select list (named country_selected above) and set the value, it’s as easy as that.

1
$('select[name=country_selected]').val('IN');

As I was using PHP it was a simple case of printing the PHP to the script.

1
<script type="text/javascript">$('select[name=country_selected]').val('<?php echo $project_region; ?>');</script>

Bookmark or share this page:

SociBook del.icio.us Digg Facebook Google Yahoo Buzz StumbleUpon