开发者

jquery set selected select option; doesn't work for dynamically added option but does for static ones

开发者 https://www.devze.com 2023-02-07 02:11 出处:网络
Here is what I have that properly populates the select list: <select id=\"countriesList\"> <option value=\"0\"> -- select country -- </option>

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) {
           开发者_JAVA百科                     $("#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>

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.

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?

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


Try doing it by hand.

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

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

So execution order is:

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

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


You probably need to use the livequery plugin...

http://docs.jquery.com/Plugins/livequery


If you're trying to select it from the same spot your example .val(500) is, you're never going to have a working result. The AJAX call is made Asynchronously and populates the information after the .val(500) has already been executed.

Move your select within the return function of the ajax call and it should work fine.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号