Zabs
Zabs

Reputation: 14142

Setting select box using jQuery on document ready

Can anyone suggest how I get to change the selected item in a select menu with jQuery - I've tried the following but without success. Using this snippet how would I use jQuery to set to value '5' for example (eg Cambridgeshire) as the 'selected' value.

<script type="text/javascript">
    $(document).ready(function() {
    $('#county_id option[value=3]').attr('selected', 'selected');
});

<html>
<select name="county_id" id="county_id">
<option value="1">Bedfordshire</option>
<option value="2">Berkshire</option>
<option value="4">Buckinghamshire</option>
<option value="5">Cambridgeshire</option>
</select>
</html>

Upvotes: 0

Views: 13425

Answers (3)

matthewvb
matthewvb

Reputation: 942

Should be able to use a jquery selector than edit the attributes.

 $('input:radio[name=county_id]')[3].checked = true;

or

 $('input:radio[name=county_id]:nth(3)').attr('checked',true);

In this case, 3 is the counter associated with Cambridgeshire (remember, counting starts at zero).

via

Upvotes: 0

Tim Withers
Tim Withers

Reputation: 12059

This should work in most cases and will automatically select the correct option.

<script type="text/javascript">
    $(document).ready(function() {
    $('#county_id').val(3);
});
</script>

Upvotes: 1

Justin Helgerson
Justin Helgerson

Reputation: 25521

You just need to use the val method.

$('#county_id').val(5);

Upvotes: 1

Related Questions