使用jquery或javascript根据以前选择的下拉值禁用下拉选项?

我有三个相同选项的下拉菜单。 我想要的是,当我从下拉列表中选择一个选项时,其他两个下拉列表中的相同选项将被禁用,除了第一个选项(选项“选择一个”)。

为此,我使用以下逻辑,但是当一个下拉列表被选择为一个值而不是从剩余的两个下拉列表中禁用该选定值时,它禁用所有这三个下拉列表,这是我不想要的。 禁用值应该发生在剩余的值上,但不会发生在当前的下拉列表中。

我怎样才能做到这一点?

 Select One 1 2 3 4 5 6 7   Select One 1 2 3 4 5 6 7   Select One 1 2 3 4 5 6 7  
 $("select.positionTypes").change(function () { $("select.positionTypes option[value='" + $(this).data('index') + "']").prop('disabled', false); $(this).data('index', this.value); $("select.positionTypes option[value='" + this.value + "']:not([value=''])").prop('disabled', true); }); 

这里是小提琴链接https://jsfiddle.net/3pfo1d1f/4/

这样做: https : //jsfiddle.net/sandenay/3pfo1d1f/7/

 $("select.positionTypes").change(function () { $("select.positionTypes option[value='" + $(this).data('index') + "']").prop('disabled', false); //reset others on change everytime $(this).data('index', this.value); $("select.positionTypes option[value='" + this.value + "']:not([value=''])").prop('disabled', true); $(this).find("option[value='" + this.value + "']:not([value=''])").prop('disabled', false); // Do not apply the logic to the current one }); 

有一种简单的方法可以做到这一点。 您可以通过简单的逻辑实现相同的function,即使对于初学者也很容易理解。

这个怎么运作:

  • 重置之前在其他dropdowns所做的所有选择
  • 禁用所有dropdowns的选定选项,不包括当前下拉列表。

JQUERY CODE:

 $(function () { $(".positionTypes").on('change', function () { var selectedValue = $(this).val(); var otherDropdowns = $('.positionTypes').not(this); otherDropdowns.find('option').prop('disabled', false); //reset all previous selection otherDropdowns.find('option[value=' + selectedValue + ']').prop('disabled', true); }); }); 

现场演示@ JSFiddle