开发者

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

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?

I was using the following example:

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

What I would need is for开发者_StackOverflow中文版 towns to be dynamic, and able to be read from a database.

Any help is greatly appreciated!

Thanks


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

Ajax Get from controller to read from database based Country which user has selected:

 <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/states from db based the country/town user has selected.

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


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>


There are benefits and risks to using Lists Of Values coded into your page, as opposed to Lists collected using an AJAX Call.

AJAX Calls are good if the lists are especially long, or based on the Current User. Hardcoded lists can be good if the list is relatively simple/small and unlikely to change frequently.

To use a hardcoded list, use the following code:

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/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜