【问题标题】:Populating One Select Box Based on the Selection in Another Select Box - JQuery?根据另一个选择框中的选择填充一个选择框 - JQuery?
【发布时间】:2011-08-17 04:39:27
【问题描述】:

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

我使用的是以下示例:

HTML:

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

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

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

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

非常感谢任何帮助!

谢谢

【问题讨论】:

标签: jquery


【解决方案1】:

正如你提到的:城镇是动态的,并且能够从数据库中读取你可以通过使用 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>

在控制器上:

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

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

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

【讨论】:

  • 亲爱的负面选民,如果您能提及为什么您认为我的回答是否定的,我将不胜感激? :)
  • 这真是一个很棒的解决方案。
  • statesProgress 是什么 - 我认为这是一个微调器,但最好明确说明 :)
  • @Mohammad 您能否重新更正此代码中缺少的括号。我正在尝试使用这个技巧。但它说它的结构不好。我是初学者,谢谢
  • @dax 是的,它是一个加载器 :)
【解决方案2】:

试试这个

<!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>

【讨论】:

    【解决方案3】:

    与使用 AJAX 调用收集的列表相比,使用编码到页面中的值列表有好处和风险。

    如果列表特别长,或者基于当前用户,AJAX 调用是很好的选择。如果列表相对简单/较小且不太可能经常更改,则硬编码列表可能会很好。

    要使用硬编码列表,请使用以下代码:

    var selectableValues = [
        {
        'title' : 'Words Starting With A' ,
        'values' : [
          'Apple' ,
          'Aardvark' ,
          'Alfalfa'
        ]
      } ,
      {
        'title' : 'Words Starting With B' ,
        'values' : [
          'Banana' ,
          'Beyond' ,
          'Belong'
        ]
      }
    ];
    
    var $select_one = $select_two = false;
    
    jQuery(function($){
    
      $select_one = $('#select_one');
      $select_two = $('#select_two');
      
        // Populate Select One
      $.each(selectableValues, function(k,v){
        $select_one.append('<option value="'+k+'">'+v.title+'</option>');
      });
      $('option:first',$select_one).text('Select...');
      $select_one.on('change',function(){
        populateSelectTwo(this.value);
      });
    
    });
    
    function populateSelectTwo( parentKey ){
      $('option',$select_two).remove();
      $select_two.append('<option value="">Select...</option>');
      $.each(selectableValues[parentKey].values, function(k,v){
        $select_two.append('<option value="'+k+'">'+v+'</option>');
      });
    }
    

    JSFiddle - https://jsfiddle.net/lucanos/8fy4m7vp/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多