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'.
Use $('select[id="salesrep"]'). val() to retrieve the selected value. Use $('select[id="salesrep"]'). val("john smith") to select a value from dropdown.
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.
$('select option:selected'). val(); will always give the current dropdown selected value.
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/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With