我有两个选择框。第一个是第二个的optgroup列表。这两个都是我的查询所需要的,但我想过滤第二个select,以便在从第一个select中选择它时只显示region optgroup和它的校园。
下面是我的代码:
<html>
<body>
<select name="region">
<option value="%">All</option>
<option value="A">Northwest</option>
<option value="B">North Central</option>
</select>
<select name="campus">
<option value="%">All</option>
<optgroup label="Northwest">
<option value="1">Gary</option>
<option value="2">Valparaiso</option>
<option value="3">East Chicago</option>
</optgroup>
<optgroup label="North Central">
<option value="4">South Bend</option>
<option value="5">Elkhart</option>
<option value="6">Warsaw</option>
</optgroup>
</select>
</body>
</html>因此,如果有人从第一个选项中选择了西北,我希望使用jQuery过滤第二个选项,这样它现在看起来就像这样:
<select name="campus">
<optgroup label="Northwest">
<option value="1">Gary</option>
<option value="2">Valparaiso</option>
<option value="3">East Chicago</option>
</optgroup>
</select>我甚至不确定这是否可能,而且这是我第一次尝试jQuery,所以我迷路了。提前谢谢。
发布于 2012-07-25 23:24:28
尝试对其他<optgroup>执行.hide()操作,然后选择所需的<optgroup>。
如下所示:
$('select[name="region"]').change(function() {
var $sel = $('select[name="campus"]'),
val = $(this).val(),
campus = $('option:selected', this).text();
if (val === '%') {
$('option,optgroup', $sel).show();
}
else {
$('optgroup, optgroup > option', $sel).hide();
$('optgroup[label="' + campus + '"]', $sel).children().andSelf().show();
}
});你不能只隐藏<optgroup>,你也需要隐藏它的子<option>s。
演示:http://jsfiddle.net/rffwW/
编辑:似乎在IE (显然还有Safari)中不起作用。Another answer建议将<option>包装在<span>s中,让我们尝试一下:
$('select[name="region"]').change(function() {
var $sel = $('select[name="campus"]'),
val = $(this).val(),
campus = $('option:selected', this).text();
$('span > optgroup', $sel).unwrap();
if (val !== '%') {
$('optgroup:not([label="' + campus + '"])', $sel).wrap('<span/>');
}
});演示:http://jsfiddle.net/rffwW/1/
发布于 2014-03-13 23:07:15
我在这里遇到了一个类似的解决方案:https://gist.github.com/robcowie/2267793
这是一个适用于选择文本而不是值的插件:
$.fn.filterGroups = function( options ) {
var settings = $.extend( {filterByText: true}, options);
return this.each(function(){
var $select = $(this);
$select.data('fg-original-groups', $select.find('optgroup').clone()).children('optgroup').remove();
$(settings.groupSelector).change(function(){
var $this = $(this);
var optgroup_label = $.trim($this.val().toUpperCase());
if(settings.filterByText)
optgroup_label = $.trim($('option:selected', $this).text());
var $optgroup = $select.data('fg-original-groups').filter("optgroup[label='" + optgroup_label + "']").clone();
$select.children('optgroup').remove();
$select.append($optgroup);
}).change();
});
};要使用该插件,请添加选择器,如下所示(我更喜欢使用ID):
$('select[name="campus"]').filterGroups({groupSelector: 'select[name="region"]' });
https://stackoverflow.com/questions/11652995
复制相似问题