一个下拉列表的内容依赖于另一个下拉列表

One drop down list contents depending on another

本文关键字:下拉列表 依赖于 另一个 一个      更新时间:2023-09-26

我试图创建两个下拉列表:下拉列表A列出一个国家。下拉列表B列出了一个城市。列表B最初为空,而列表A由国家填充。用户可以选择一个国家,从而使列表B自动列出列表A中的城市。这些自然会来自数据库,所以这不是我问题的目标。我的问题是如何绑定列表B以依赖于列表a。我花了好几个小时研究答案并尝试了各种jquery和javascript方法。我被困在试图让列表B通过使用列表A的更改方法来响应列表A,但到目前为止,似乎没有任何作用,我也无法触发列表B在添加测试值方面的响应。

我该怎么做?

这是工作小提琴:相对下拉

$(function() {
var cities = {
    'INDIA': ['Delhi', 'Mumbai', 'Bangalore', 'Ahmedabad'],
    'USA': ['London', 'Los Angeles', 'Austin', 'New York']
};
var hashFunc = function(country, city){
    return country + "." + city;
};
//The form
var form = new Backbone.Form({
    schema: {
        country: { type: 'Select', options: ['INDIA', 'USA'] },
        city: { type: 'Select', options: cities.INDIA},
    }
}).render();
form.on('country:change', function(form, countryEditor) {
    var country = countryEditor.getValue(),
        newOptions = cities[country];
    form.fields.city.editor.setOptions(newOptions); 
});  
//Add it to the page
$('body').append(form.el);
});

当任何选项被选中时,根据它的值,您可以为另一个选择创建动态选项。

$('#A').change(function() {
  if($('#A:selected').val() == "India"){
     $("<option></option>", 
        {value: "Surat", text: "Surat"})
       .appendTo('#B');
  } 
});
$('#select1').change(function(){
callAjax(this.value);
});
function callAjax(value1)
{
//here write the code for ajax
}

在没有数据库方案的情况下很难回答这个问题。

假设您的DB看起来像

    Countrys
 +--------------+
 | New Zealand  | 
 +--------------+
 | Australia    |
 +--------------+
 | India        |
 +--------------+
 Towns
    Country       Town
 +--------------+---------------+
 | NZL          | Auckland      |
 +--------------+---------------+
 | NZL          | Wellington    |
 +--------------+---------------+
 | NZL          | Christchurch  |
 +--------------+---------------+
 | AU           | Sydney        |
 +--------------+---------------+
 | AU           | Wagawaga      |
 +--------------+---------------+
 | AU           | Brisbane      |
 +--------------+---------------+
 | IN           | Mumbai        |
 +--------------+---------------+

……等等

First Select

  <select onchange ="town()" id="country">
  <option value = "NZ">New Zealand</option> 
  <option value = "AU">Australia</option>
  <option value = "IN">India</option>
  </select>

第二个

  <select id="towns"></select>
Javascript

  function town()
  {
  var town = $('#country').val()
  $.ajax({
        type: "POST",
        url: "http://yourserver/rpc.php",
        data: { method: 'get_towns'},
        dataType: "json",
        timeout: 10000, // in milliseconds
        success: function(data) {
            $("#towns".html(data.towns)
            },
        error: function(request, status, err) {
            if(status == "timeout") {
                $.ui.hideMask();
               alert('This is taking too long. You could try again now, or wait and try again later.');
    }
    }
    }); 

}

从db返回json中的城镇