这被称为Populate one dropdown based on selection in another的副本,但是我需要一个跨浏览器的jQuery解决方案。我发现很多都是香草JS或PHP。只需要纯HTML和jQuery。 (我原来的问题:How to populate second <select> based on first <select> value)
我有两个<select>
下拉菜单,其中第二个下拉菜单需要使用在第一个下拉菜单中选择的值来填充。我该怎么做?
<label for="allmakes" style="display: none;">All Makes</label>
<select class="search-form__select" id="allmakes" name="allmakes">
<option selected disabled>All Makes</option>
<option value="audi">Audi</option>
<option value="bmw">BMW</option>
<option value="nissan">Nissan</option>
<option value="vauxhall">Vauxhall</option>
</select>
<label for="allmodels" style="display: none;">All Models</label>
<select class="search-form__select" id="allmodels" name="allmodels">
<option selected disabled class="all-models">All Models</option>
<option value="audi" class="audi" disabled>A1</option>
<option value="audi" class="audi" disabled>A2</option>
...
<option value="bmw" class="bmw" disabled>1 Series</option>
<option value="bmw" class="bmw" disabled>2 Series</option>
...
<option value="nissan" class="nissan" disabled>GT-R</option>
<option value="nissan" class="nissan" disabled>Juke</option>
...
<option value="vauxhall" class="vauxhall" disabled>Astra</option>
<option value="vauxhall" class="vauxhall" disabled>Corsa</option>
...
</select>
@ King11提供了一些帮助解决我的其他问题的方法,但是却导致了Safari上的一些问题(默认情况下,我必须添加禁用并关闭这些功能),而在Edge(我认为是IE)上,选择弹出-out菜单会在禁用选项所在的位置显示大量空白,而我似乎无法为此添加某种自动高度。
var audi = $('.audi'),
bmw = $('.bmw'),
nissan = $('.nissan'),
vauxhall = $('.vauxhall');
$('#all-makes').change(function() {
$('.all-models').prop('selected', true);
// .show() and .hide() working on Chrome, Firefox and Opera.
// Added attr() and removeAttr() to work on Safari but the disabled options are still visible. Would ideally like to hide these.
if ($(this).val() === 'audi') {
audi.show().removeAttr('disabled');
bmw.hide().attr('disabled', 'disabled');
nissan.hide().attr('disabled', 'disabled');
vauxhall.hide().attr('disabled', 'disabled');
} else if ($(this).val() === 'bmw') {
audi.hide().attr('disabled', 'disabled');
bmw.show().removeAttr('disabled');
nissan.hide().attr('disabled', 'disabled');
vauxhall.hide().attr('disabled', 'disabled');
} else if ($(this).val() === 'nissan') {
audi.hide().attr('disabled', 'disabled');
bmw.hide().attr('disabled', 'disabled');
nissan.show().removeAttr('disabled');
vauxhall.hide().attr('disabled', 'disabled');
} else if ($(this).val() === 'vauxhall') {
audi.hide().attr('disabled', 'disabled');
bmw.hide().attr('disabled', 'disabled');
nissan.hide().attr('disabled', 'disabled');
vauxhall.show().removeAttr('disabled');
}
});
答案 0 :(得分:1)
我将使用jQuery从第二个选项集中动态添加和删除选项。
我找到了这篇文章:
https://paulund.co.uk/add-and-remove-options-in-select-using-jquery
In the gist is this:
// Remove options
$("#selectBox option[value='option1']").remove();
// Add options
$("#selectBox").append('<option value="option6">option6</option>');
我已经在所有浏览器中看到了这项工作。