JQuery.val () method cannot set value in select list?

The following code failed when I upgraded to 1.4.1 and worked fine when I rolled back to 1.3.2.

var ddlCountry = $("#<%= this.ddlCountry.ClientID %>"); if (ddlCountry.val() == "") { ddlCountry.val(address.country); ddlCountry.change(); } 

By the way, the problem is that the value of the <select> list is never set.

Yes, all this is wrapped in $(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()); } }); 
+4
source share
1 answer

If you set the value , this will work, in jQuery 1.4 there should be a value different from the text, for 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 should not be: $("#ddlCountry").val("1")

Alternatively, if you cannot change the drop-down list, you can search and select based on the text as follows:

 ddlCountry.filter(function() { return $(this).text() == address.country; })[0].selected = true; 

For reference, there has been a change to jQuery . From 1.4 notes:

.val ("...") by option or checkbox is no longer ambiguous (it will always select by value now, and not by text value). (Commit)

+6
source

Source: https://habr.com/ru/post/1303019/


All Articles