根据以前的选择删除下拉条目

时间:2012-07-13 10:55:19

标签: php jquery html5

我已经通过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中不需要该选项',她选择其他东西并且该选项重新出现在其他下拉列表中。上面的代码删除了选项,然后无法检索它们,直到你点击它们全部消失为止。

2 个答案:

答案 0 :(得分:0)

这实际上做了你想要的......这是基于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函数中考虑自己的做法。

答案 1 :(得分:0)

我最终使用了这个,因为它很简洁......

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];
});
});
});
相关问题