jQuery根据选择的另一个SELECT删除SELECT选项(需要支持所有浏览器) [英] jQuery remove SELECT options based on another SELECT selected (Need support for all browsers)
本文介绍了jQuery根据选择的另一个SELECT删除SELECT选项(需要支持所有浏览器)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我有这个下拉列表:
<select id="theOptions1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
我想要它,以便当用户选择1时,这是用户可以选择的东西下拉2:
I want it so that when the user selects 1, this is the thing that the user can choose for dropdown 2:
<select id="theOptions2">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
或者如果用户选择2:
<select id="theOptions2">
<option value="a">a</option>
<option value="b">b</option>
</select>
或者如果用户选择3:
<select id="theOptions2">
<option value="b">b</option>
<option value="c">c</option>
</select>
我尝试了这里发布的代码:
jQuery禁用基于选择Radio的SELECT选项(需要支持所有浏览器)
I tried the code posted here: jQuery disable SELECT options based on Radio selected (Need support for all browsers)
但它不适用于选择。
请帮忙!
谢谢!
Please help! Thank you!
更新:
我非常喜欢Paolo Bergantino的答案:
jQuery禁用基于Radio选择的SELECT选项(需要支持所有浏览器) )
无论如何要修改它以使用选择而不是单选按钮吗?
Is there anyway to modify this to work with selects instead of radio buttons?
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)
);
}
});
});
});
};
推荐答案
这有效(在Safari 4.0.1,FF中测试) 3.0.13):
This works (tested in 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;
}
});
});
美丽的用户界面:
<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>
这篇关于jQuery根据选择的另一个SELECT删除SELECT选项(需要支持所有浏览器)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文