jQuery.val() method failing to set value on a select list?
javascript, jquery
Solution
If you are setting the value, this will work, in jQuery 1.4 is must be the value not text, example:
<select id="ddlCountry">
<option value="1">A</option>
<option value="2">B</option>
</select>
In jQuery 1.3 this works: `$("#ddlCountry").val("A")` In 1.4 it doesn't it must be: `$("#ddlCountry").val("1")`
Alternatively if you can't change your dropdown, you can search for and select based on text like this:
ddlCountry.filter(function() {
return $(this).text() == address.country;
})[0].selected = true;
For reference, here's the jQuery change that happened. From the 1.4 notes:
.val(“…”) on an option or a checkbox is no longer ambiguous (it will always select by value now, not by text value). (Commit)
Problem
The following code failed when I upgraded to 1.4.1, and worked ok when I rolled back to 1.3.2. ``` var ddlCountry = $("#<%= this.ddlCountry.ClientID %>"); if (ddlCountry.val() == "") { ddlCountry.val(address.country); ddlCountry.change(); } ``` BTW the problem is that the value of the `<select>` list is never set. Yes, this is all wrapped up in a `$(document).ready` :) EDIT: For reference this is the code I used: ``` ddlCountry.find("option").each(function() { if ($(this).text() == address.country) { ddlCountry.val($(this).val()); } }); ```