Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: set selected value of dropdown list?

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'.

like image 488
simon Avatar asked Apr 27 '11 20:04

simon


People also ask

How can I set the value of a Dropdownlist using jQuery?

Use $('select[id="salesrep"]'). val() to retrieve the selected value. Use $('select[id="salesrep"]'). val("john smith") to select a value from dropdown.

How do I set a dropdown selected value?

Using the jQuery change() method; you can set the selected value of dropdown in jquery by using id, name, class, and tag with selected html elements; see the following example for that: Example 1 :- Set selected value of dropdown in jquery by id. Example 2 :- Set selected value of dropdown in jquery by Name.

How can get default selected value of dropdown in jQuery?

$('select option:selected'). val(); will always give the current dropdown selected value.


2 Answers

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/

like image 144
mattsven Avatar answered Sep 24 '22 13:09

mattsven


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.

like image 26
mVChr Avatar answered Sep 23 '22 13:09

mVChr