jquery set selected select option; doesn't wor

2019-06-08 19:31发布

问题:

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>

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.

回答1:

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



回答2:

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.



回答3:

You probably need to use the livequery plugin...

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