Osc*_*car 12 javascript jquery select
说我有这个下拉列表:
<select id="theOptions1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
Run Code Online (Sandbox Code Playgroud)
我想要它,以便当用户选择1时,这是用户可以选择下拉2的东西:
<select id="theOptions2">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
Run Code Online (Sandbox Code Playgroud)
或者,如果用户选择2:
<select id="theOptions2">
<option value="a">a</option>
<option value="b">b</option>
</select>
Run Code Online (Sandbox Code Playgroud)
或者,如果用户选择3:
<select id="theOptions2">
<option value="b">b</option>
<option value="c">c</option>
</select>
Run Code Online (Sandbox Code Playgroud)
我尝试了这里发布的代码: jQuery禁用基于Radio选择的SELECT选项(需要支持所有浏览器)
但它不适用于选择.
请帮忙!谢谢!
更新:我真的很喜欢Paolo Bergantino的答案: jQuery禁用基于Radio选择的SELECT选项(需要支持所有浏览器)
反正有没有修改它来使用选择而不是单选按钮?
jQuery.fn.filterOn = function(radio, values) {
return this.each(function() {
var select = this;
var options = [];
$(select).find('option').each(function() {
options.push({value: $(this).val(), text: $(this).text()});
});
$(select).data('options', options);
$(radio).click(function() {
var options = $(select).empty().data('options');
var haystack = values[$(this).attr('id')];
$.each(options, function(i) {
var option = options[i];
if($.inArray(option.value, haystack) !== -1) {
$(select).append(
$('<option>').text(option.text).val(option.value)
);
}
});
});
});
};
Run Code Online (Sandbox Code Playgroud)
kar*_*m79 15
这工作(在Safari 4.0.1,FF 3.0.13中测试):
$(document).ready(function() {
//copy the second select, so we can easily reset it
var selectClone = $('#theOptions2').clone();
$('#theOptions1').change(function() {
var val = parseInt($(this).val());
//reset the second select on each change
$('#theOptions2').html(selectClone.html())
switch(val) {
//if 2 is selected remove C
case 2 : $('#theOptions2').find('option:contains(c)').remove();break;
//if 3 is selected remove A
case 3 : $('#theOptions2').find('option:contains(a)').remove();break;
}
});
});
Run Code Online (Sandbox Code Playgroud)
而美丽的用户界面:
<select id="theOptions1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br />
<select id="theOptions2">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
Run Code Online (Sandbox Code Playgroud)
您可以在<option>s中添加要存储的类,其中包含以下每个值#theOptions1:
<select id="theOptions2">
<option value="a" class="option-1 option-2">a</option>
<option value="b" class="option-1 option-2 option-3">b</option>
<option value="c" class="option-1 option-3">c</option>
</select>
Run Code Online (Sandbox Code Playgroud)
然后这样做:
$(function() {
var allOptions = $('#theOptions2 option').clone();
$('#theOptions1').change(function() {
var val = $(this).val();
$('#theOptions2').html(allOptions.filter('.option-' + val));
});
});
Run Code Online (Sandbox Code Playgroud)