37

What's wrong with this code?

jQuery

$(document).ready(function() { $("#routetype").val('quietest'); )}; 

HTML

<select id="routetype" name="routetype"> <option value="fastest">Fastest</option> <option selected="true" value="balanced">Balanced</option> <option value="quietest">Quietest</option> </select> 

Fiddle

It gives me 'Balanced' as the selected option, not 'Quietest'.

3
  • 6
    You need to select jQuery in the dropdown on the left and you have a syntax error because the $(document).ready should end with }); not )}; See: jsfiddle.net/x3UyB/2 Commented Apr 27, 2011 at 20:21
  • 1
    @mVChr you should post that as an answer =) Commented Apr 27, 2011 at 20:24
  • @mVChr thank you, please post as an answer :) Commented Apr 27, 2011 at 20:52

3 Answers 3

68

UPDATED ANSWER:

Old answer, correct method nowadays is to use jQuery's .prop(). IE, element.prop("selected", true)

OLD ANSWER:

Use this instead:

$("#routetype option[value='quietest']").attr("selected", "selected"); 

Fiddle'd: http://jsfiddle.net/x3UyB/4/

Sign up to request clarification or add additional context in comments.

3 Comments

what if I want to use a variable instead of a hard-coded value (like "quietest"?
@Kevin You can always do $("#routetype option").each() to compare dropdown values, or just $("#routetype option[value='"+option_value+"']");
@mattsven, I get selected='selected' on two options this way. just an FYI.
32

You need to select jQuery in the dropdown on the left and you have a syntax error because the $(document).ready should end with }); not )}; Check this link.

1 Comment

Thanks. Actually the issue was because I was working with jQuery Mobile and you need to call $("#routetype").selectmenu('refresh'); as well to update what is shown.
4

You can select dropdown option value by name

jQuery("#option_id").find("option:contains('Monday')").each(function() { if( jQuery(this).text() == 'Monday' ) { jQuery(this).attr("selected","selected"); } }); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.