我有几个带有一些选项的SELECT标签。
选定的选项在所有列表中必须是唯一的,而未选择的选项是共享的,并且每个选项都应该可用。
然后,当在一个SELECT中选择某个选项时,应该从其他列表中删除它。当某个选项未被选中时,它应该在所有列表中再次可用。
我的问题是我无法找到(未)选择的选项。我在SELECT上尝试了onChange事件,但无法找到最后选择的选项。此外,我在OPTION标签上尝试了各种事件,但未触发事件。
当然,如果我在JavaScript中使用SELECT的值,那么我只是用逗号分隔所有值,而我无法从中添加或删除哪个值。
是否可以在OPTION标签上使用某些事件来获取当前选中或未选中项目的值?
谢谢!
答案 0 :(得分:1)
此方法将更新所有选择,以便在选择项目后将其从对应项中删除。相反,取消选择也会将选项添加回其他人
var $selects = $('select'),
$storedOpts = $selects.first().children().clone();
$selects.change(function(){
$selects.not(this).each(function(){
var otherVals = $.map($selects.not(this).find(':selected'),function(opt){
return opt.value
});
var currVal = $(this).val();
var $options = $storedOpts.clone().filter(function(_, option){
return $.inArray(option.value, otherVals) == -1;
})
$(this).html($options).val(currVal);
});
});
的 DEMO 强>
答案 1 :(得分:0)
您可以迭代select元素中的所有选项,并确定是否选择了每个选项:
var selectele = document.getElementById('your_select_id');
for(var i = 0; i < selectele.options.length; i++){
var option = selectele.options[i];
if(option.selected){
// this option is selected
}else{
// this option is not selected
}
}
使用此功能,您可以在javascript代码中单独列出所有可用选项,并在任何更改时重建整个选项列表。然后,您不必考虑任何选择列表可能发生变化的每种方式。
答案 2 :(得分:0)
您可以在jQuery中使用.data()
来存储以前选择的值以供稍后使用,然后只绑定到更改事件:
示例:强>
$('.foo').change(function() {
// setup
var option = $(this).find(':selected'),
text = option.text(),
self = $(this),
data = $(this).data('prev'),
foos = $('.foo');
// unhide
if (text === '-- select --') {
foos.not(self).each(function() {
var unhide = $(this).children('option').filter(function() {
return $(this).html() == data; // <-- previous
});
unhide.show();
});
} else { // hide
foos.not(self).each(function() {
var hide = $(this).children('option').filter(function() {
return $(this).html() == text; // <-- current
});
hide.hide();
});
}
// store the previously selected value
$(this).data('prev', text);
});
&#13;
.foo {
margin: 15px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="foo">
<option>-- select --</option>
<option>bar</option>
<option>bim</option>
<option>baz</option>
</select>
<select class="foo">
<option>-- select --</option>
<option>bar</option>
<option>bim</option>
<option>baz</option>
</select>
<select class="foo">
<option>-- select --</option>
<option>bar</option>
<option>bim</option>
<option>baz</option>
</select>
&#13;