我正在尝试创建一个下拉列表,该下拉列表根据前一个下拉列表中选择的选项填充列表,但第二个下拉列表在某种程度上不起作用。在这里,我找到了一个网站http://www.9lessons.info/2010/08/dynamic-dependent-select-box-using.html,这正是我想要的,但它不适合我。它是单独工作的,但是当我将它添加到我现有的代码中时,它无法正常工作。请帮忙!
答案 0 :(得分:0)
我认为这正是您所寻找的,请在下面进行测试并告诉我。
var countries = [{id: 1, name: "United States"}, {id: 2, name: "Canada"}, {id: 3, name: "United Kingdom"}, {id: 4, name: "France"}];
var states = [{id: 1, country_id: 1, name: "OH"}, {id: 2, country_id: 1, name: "NY"}, {id: 3, country_id: 2, name: "Montreal"}, {id: 4, country_id: 2, name: "Ontario"}, {id: 5, country_id: 3, name: "Scotland"}, {id: 6, country_id: 3, name: "Ireland"}, {id: 7, country_id: 4, name: "Normandy"}];
var option = '';
$.each(countries, function( index, value ) {
option += '<option value="'+ value.id + '">' + value.name + '</option>';
});
$('#country').append(option);
$('#country').on('change', function (e) {
var id = $(this).val();
$('#state').empty()
var results = $.grep(states, function(e){ return e.country_id == id; });
var stateOptions = '';
$.each(results, function( index, value ) {
stateOptions += '<option value="'+ value.id + '">' + value.name + '</option>';
});
$('#state').append(stateOptions);
});
$('#country').trigger('change');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="country">
</select>
<select id="state">
</select>