如何禁用已在另一个中选择的选项?

我有五个具有不同值的HTML选项,但选项具有相同的文本。 如何比较文本选项而不是值,并在每个其他选择中禁用相应的选项? 例如,如果我有:

   test-1   test-2   test-3     test-1   test-2   test-3     test-1   test-2   test-3     test-1   test-2   test-3     test-1   test-2   test-3   

假设用户在最后一个select选择了test-1 select 。 这应该禁用其他选择中的相应option 。 我怎样才能做到这一点?

如果我理解正确,可能是这样:

 var $selects = $('select'); $selects.on('change', function() { var $select = $(this), $options = $selects.not($select).find('option'), selectedText = $select.children('option:selected').text(); var $optionsToDisable = $options.filter(function() { return $(this).text() == selectedText; }); $optionsToDisable.prop('disabled', true); }); //to apply initial selection $selects.eq(0).trigger('change'); 

jsFiddle: 例子

扩展@ IgorDymov的答案(信用应该归他),这可能是我要做的(见小提琴 ):

 var $selects = $('select'); $selects.on('change', function() { $("option", $selects).prop("disabled", false); $selects.each(function() { var $select = $(this), $options = $selects.not($select).find('option'), selectedText = $select.children('option:selected').text(); $options.each(function() { if($(this).text() == selectedText) $(this).prop("disabled", true); }); }); }); $selects.eq(0).trigger('change'); 

这样,每次创建新选项时,我们都会完全刷新选择,这意味着属性将再次重新启用。 你会注意到,我减少了选择次数并增加了选项数量,这样你就不会陷入同时禁用所有选项的情况,我认为这是最有意义的。

长度的例子

 var $selects = $('select'); available = {}; // Get the text of options from the dropdown // and store in a object hash $('option', $selects.eq(0)).each(function (i) { var val = $.trim($(this).text()); available[val] = false; }); $selects.change(function () { var $this = $(this); var selectedVal = $.trim($this.find('option:selected').text()); // set that value to true available[selectedVal] = true; $selects.not(this).each(function () { $('option', this).each(function () { var optText = $.trim($(this).text()), optCheck = available[optText]; $(this).prop('disabled', optCheck ); }); }); }).change(); // Trigger once to add options at load of first choice 

检查小提琴

要获取当前所选选项的选项标记之间的文本,您将执行以下操作:

 $('option[value="'+$('select').val()+'"]').text(); 

它转换为:获取选项的文本,其值与select中当前列出的值相同