我已经在stackoverflow中找到了答案,现在已经差不多了,但需要一些帮助。
我有多个下拉列表,其中包含相同的选项。例如,具有以下内容的三个相同列表:
<label for='distlist_1'>Distribution List 1</label>
<select name='distlist_1'>
<option value=''>Please Select:</option>
<option value='1'>All</option>
<option value='2'>All Managers</option>
<option value='3'>Leavers</option>
</select>
唯一的区别是名称,例如distlist_1、2、3等。如果需要,我可以添加id。
当用户在第一个下拉列表中选择一个选项时,我需要将其从所有其他下拉列表中删除。我找到了一个这样做的脚本。
$('option').click(function(){
$('option:contains(' + $(this).html() +')').not(this).remove();
});
但我需要它,这样,如果用户决定,"等等,我根本不需要下拉列表1中的那个选项",她会选择其他选项,该选项会再次出现在其他下拉列表中。上面的代码删除了这些选项,然后没有办法检索它们,直到你点击足够多,它们都消失了。
这实际上是你想要的。。。这是基于jquery 1.7和on()事件绑定
$(document).ready(function (){
$('select').on('focus', function() {
// on focus save the current selected element so you
// can place it back with all the other dropdowns
var current_value = $(this).val();
// bind the change event, with removes and adds elements
// to the dropdown lists
$(this).one('change.tmp', { v : current_value }, function(e)
{
if ($(this).val() != '')
{ // do not remove the Please select options
$('option[value="' + $(this).val() + '"]')
.not($('option[value="' + $(this).val() + '"]', $(this)))
.remove();
}
if (e.data.v != '')
{ // do not add the Please select options
$('select').not($(this)).append($('option[value="' + e.data.v + '"]', $(this)).clone());
}
});
// on blur remove all the eventhandlers again, this is needed
// else you don't know what the previously selected item was.
$(this).on('blur.tmp', { v : current_value}, function (e)
{
$(this).off('blur.tmp');
$(this).off('change.tmp');
});
});
});
它唯一不做的就是把所有东西都按正确的顺序排列。您必须在.append函数中考虑自己的方法。
我最终使用了它,因为它很简洁。。。
jQuery(document).ready(function() {
var selects = $('.mapping')
selects.change(function() {
var vals = {};
selects.each(function() {
vals[this.value] = true;
}).get();
selects.not(this).children().not(':selected').not(':first-child').each(function() {
this.disabled = vals[this.value];
});
});
});