根据另一个选择框中的选择填充一个选择框 - JQuery?

sha*_*h17 17 jquery

我试图根据第一个选择框中的选择填充一个选择框.我在网上看了一下,发现了很多关于硬编码选项的有用信息,但我需要我的选项来自查询(比如coldfusion中的cfquery).我知道cfquery是服务器端的,所以我不能将它包含在我的jquery中,但还有其他选择吗?

我使用以下示例:

HTML:

<select id="counties">
    <option> </option>
    <option> somerset </option>
    <option> hertfordshire </option>
</select>

<select id="towns" disabled="true">
</select>
Run Code Online (Sandbox Code Playgroud)

JS:

var countyTowns = [
    ["Bath", "Bristol"],
    ["Letchworth", "Hitchin"]
];

$("#counties").change(function() {
    var county = this.selectedIndex - 1;
    $("#towns").empty();
    if (county === -1) {
        $("#towns").attr("disabled", true);
    } else {
        var towns = countyTowns[county];
        for (var i = 0; i < towns.length; i++) {
            $("#towns").append($("<option></option>").text(towns[i]));
        }
        $("#towns").attr("disabled", false);
    }
});
Run Code Online (Sandbox Code Playgroud)

我需要的是城镇是动态的,能够从数据库中读取.

任何帮助是极大的赞赏!

谢谢

Edg*_*ado 12

这里有一些例子:

  • @EdgarVillegasAlvarado我意识到你的答案解决了这个问题.但是,我经常看到标记为可能重复的问题(今天标记为一个),仅链接答案应包含从中获取的代码.如果这些网站/页面不再存在,答案(和问题)对任何人都没用.*只是说*. (9认同)
  • 是的,这不是一个好的答案,如果不是因为它已经存在了6年,我想它不会有15个赞成! (2认同)

Moh*_*mad 2

正如您提到的:城镇是动态的,并且能够从数据库中读取,您可以通过使用ajax传递来获取动态数据。

Ajax 从控制器获取以从用户选择的基于国家/地区的数据库中读取:

 <script>
        $(document).ready(function () {
           $("#counties").on('change', function () {
                var selectedItem = $(this).val();
                var ddlStates = $("#towns"); // will be update after success ajax call
                var statesProgress = $("#states-loading-progress");
                statesProgress.show();
                $.ajax({     // get states/towns from db from controller
                    cache: false,
                    type: "GET",
                    url: "@(Url.RouteUrl("GetStatesByCountryId"))", 

                    data: { "countryId": selectedItem, "addSelectStateItem": "true" },
                    success: function (data) { 
                        ddlStates.html('');
                        $.each(data, function (id, option) {
                            ddlStates.append($('<option></option>').val(option.id).html(option.name)); 
                        });  // populating result 
                        statesProgress.hide(); // hide loader
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert('Failed to retrieve states.');
                        statesProgress.hide();
                    }
                });
            });
        });
    </script>
Run Code Online (Sandbox Code Playgroud)

在控制器上:

  public virtual IActionResult GetStatesByCountryId(string countryId, bool addSelectStateItem)
    {
        var model = _countryModelFactory.GetStatesByCountryId(countryId, addSelectStateItem);
        return Json(model);
    }
Run Code Online (Sandbox Code Playgroud)

然后在数据访问层 上,我根据国家/城镇用户选择的数据库从数据库_countryModelFactory.GetStatesByCountryId()获取城镇/州。

更新: 这是我从数据库(动态国家/城镇)检索州/城镇并将其填充到我的代码中的方式selectbox

  • 这确实是一个很棒的解决方案。 (2认同)