最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery.val() method failing to set value on a select list? - Stack Overflow

programmeradmin2浏览0评论

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());
                }
            });

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());
                }
            });
Share Improve this question edited Mar 4, 2010 at 9:01 AndrewVos asked Mar 3, 2010 at 16:55 AndrewVosAndrewVos 1,2952 gold badges14 silver badges25 bronze badges 3
  • It's a string value which es from the Google AJAX Search API Geolocation feature. – AndrewVos Commented Mar 3, 2010 at 17:01
  • What 'value' of the select are you trying to set? The selected item? – Lazarus Commented Mar 3, 2010 at 17:02
  • I'm trying to match the item that has the same text as address.country and select it. – AndrewVos Commented Mar 3, 2010 at 17:29
Add a ment  | 

1 Answer 1

Reset to default 6

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)

发布评论

评论列表(0)

  1. 暂无评论