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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5861090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:55:23  来源:igfitidea点击:

Populating One Select Box Based on the Selection in Another Select Box - JQuery?

jquery

提问by shawleigh17

I am trying to populate one select box based on the selection made in the first select box. I've looked online, and found a lot of helpful information on hard-coded options, but I need my options to come from a query (like cfquery in coldfusion). I know that a cfquery is server-side, so I cannot include it in my jquery, but is there another option?

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

I was using the following example:

我正在使用以下示例:

HTML:

HTML:

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

<select id="towns" disabled="true">
</select>

JS:

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

What I would need is for towns to be dynamic, and able to be read from a database.

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

Any help is greatly appreciated!

任何帮助是极大的赞赏!

Thanks

谢谢

回答by Mohammad

as you mentioned that : towns to be dynamic, and able to be read from a databaseyou can get dynamic data by passing it with ajax.

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

Ajax Get from controllerto read from database based Countrywhich user has selected:

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>

And on controller :

在控制器上:

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

Then on Data access layer_countryModelFactory.GetStatesByCountryId()i get towns/statesfrom db based the country/town user has selected.

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

Update :It's the way i retrieving states/towns from db (dynamic country/towns) and populating them to selectboxin my code.

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

回答by Jobelle

Try this

尝试这个

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
 $("#counties").change(function() {
    if($(this).val()){
    $("#towns").attr('disabled',false);


  //var towns = countyTowns[county];
   // for (var i = 0; i < towns.length; i++) {
      //  $("#towns").append($("<option></option>").text(towns[i]));
   // }


      optionText = 'Premium'; 
      optionValue = 'premium'; 

      $('#towns').append(`<option value="${optionValue}"> 
                                       ${optionText} 
                                  </option>`); 
    }
    else {
     $("#towns").attr('disabled',true);
     $("#towns").empty();


    }
  });
});
</script>
</head>
<body>

<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
<select id="counties">
    <option> </option>
    <option> somerset </option>
    <option> hertfordshire </option>
</select>

<select id="towns" disabled="true">
</select>


</body>
</html>