[英]Cascading dropdown on Javascript
级联下拉列表在第一个下拉列表上工作正常,无法识别第二个下拉列表。 这里缺少一些小东西。 我尝试了一些选项,但是javascript并未附加到第二个调用。 有没有办法动态添加它?
<label class="page1">Country</label>
<div class="tooltips" title="Please select the country that the customer will primarily be served from">
<select id="country" name="country" placeholder="Phantasyland">
<option></option>
<option>Germany</option>
<option>Spain</option>
<option>Hungary</option>
<option>USA</option>
<option>Mexico</option>
<option>South Africa</option>
<option>China</option>
<option>Russia</option>
</select>
</div>
<br />
<br />
<label class="page1">Location</label>
<div class="tooltips" title="Please select the city that the customer is primarily to be served from.">
<select id="location" name="location" placeholder="Anycity"></select>
</div>
<label class="page1">Country</label>
<div class="tooltips" title="Please select the country that the customer will primarily be served from">
<select id="country" name="country" placeholder="Phantasyland">
<option></option>
<option>Germany</option>
<option>Spain</option>
<option>Hungary</option>
<option>USA</option>
<option>Mexico</option>
<option>South Africa</option>
<option>China</option>
<option>Russia</option>
</select>
</div>
<br />
<br />
<label class="page1">Location</label>
<div class="tooltips" title="Please select the city that the customer is primarily to be served from.">
<select id="location" name="location" placeholder="Anycity"></select>
</div>
使用Javascript:
jQuery(function($) {
var locations = {
'Germany': ['Duesseldorf', 'Leinfelden-Echterdingen', 'Eschborn'],
'Spain': ['Barcelona'],
'Hungary': ['Pecs'],
'USA': ['Downers Grove'],
'Mexico': ['Puebla'],
'South Africa': ['Midrand'],
'China': ['Beijing'],
'Russia': ['St. Petersburg'],
}
var $locations = $('#location');
$('#country').change(function () {
var country = $(this).val(), lcns = locations[country] || [];
var html = $.map(lcns, function(lcn) {
return '<option value="' + lcn + '">' + lcn + '</option>'
}).join('');
$locations.html(html)
});
});
问题是您在HTML元素上使用重复ID。 在HTML文档中的多个元素上具有相同的ID是无效的。 您还需要更改名称属性,否则您的表单将仅包含最后一个元素的值。
您可以将类添加到顶级类别选择元素
<select id="country1" class="country" name="country1" placeholder="Phantasyland">
...
</select>
<select id="country2" class="country" name="country2" placeholder="Phantasyland">
...
</select>
然后,您可以在子类别中添加一个属性,该属性链接到父选择元素
<select data-parent="country1" name="location1" placeholder="Anycity"></select>
<select data-parent="country2" name="location2" placeholder="Anycity"></select>
然后将处理程序绑定到country
类
$('.country').change(function () {
var id = $(this).attr('id');
var $locations = $('[data-parent=' + id + ']');
var country = $(this).val(), lcns = locations[country] || [];
var html = $.map(lcns, function(lcn) {
return '<option value="' + lcn + '">' + lcn + '</option>'
}).join('');
$locations.html(html)
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.