jQuery的集合中选择选择选项;不适用于动态添加选项工作,但确实为静态的 [英] jquery set selected select option; doesn't work for dynamically added option but does for static ones

查看:155
本文介绍了jQuery的集合中选择选择选项;不适用于动态添加选项工作,但确实为静态的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我有一个正确填充选择列表:

Here is what I have that properly populates the select list:

            <select id="countriesList">
                <option value="0"> -- select country -- </option>
                <option value="500"> 500 </option>
            </select>

            <script type="text/javascript">
                $(function () {
                    // load the countries list
                    $.getJSON(
                        "/StaticData/GetAllCountries/",
                        function (countries) {
                            // iterate each returned country and add it to the countries select list.
                            $.each(countries, function (i, country) {
                                $("#countriesList").append("<option value='" + country.Id + "'>" + country.Description + "</option>");
                            });
                        });

                    // set the selected country based on the model's delivered CountryId value
                    $('#countriesList').val(500);
                });
            </script>

人口的伟大工程,而是由脚本添加不让它选择该选项的元素之一调用.VAL(),但作为一个例子,静态定义选项500当我打电话.VAL(正常工作)就可以了。

The population works great, but calling .val() on one of the option elements added by the script does not make it selected, but as an example, the statically defined option "500" works fine when I call .val() on it.

我是相当新的jQuery的,但不是编程,我做我的方式进入浏览器编程。任何提示将是有益的。你需要什么?

I'm fairly new to jquery, but not programming, as I make my way into browser programming. Any tips would be useful. What else do you need?

所以选择填充和形式呈现设置这个脚本code是直接表td标签里面坐着。

This script code is sitting directly inside a table td tag so the select is populated and set as the form is rendered.

推荐答案

尝试做手工。

var select = document.getElementBydId("countriesList");
for (var i  = 0; i < select.options.length; i++) {
    if (select.options[i].value === "500") {
        select.selectedIndex = i;
    }
}

等待。问题是你做的AJAX是与异步并具有回调

Wait. The problem is your doing AJAX with is async and has a callback

所以执行顺序是:


  • 的getJSON

  • 在选择
  • SETVAL
  • 添加选项来选择。

  • getJSON
  • setval on select
  • add options to select.

所以添加 $(#countriesList)。VAL(500)来你的回调函数的结尾

So add that $("#countriesList").val(500) to the end of your callback function

这篇关于jQuery的集合中选择选择选项;不适用于动态添加选项工作,但确实为静态的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆