如果在其他中选中,则禁用jQuery 选项

我试图在任何选择中选择它时尝试禁用该选项

因此,例如,如果name =“select1”选择了选项“Test 2”,那么我希望在两个select语句中禁用“Test 2”…如果检查了其他内容,则重新启用前一个选项。

我在这里写了一个示例脚本,我认为这样可以让我’接近’……但它让我远离这里。 任何帮助,将不胜感激。

 $(document).ready(function(){ $("select").change(function() { $("select").find("option:selected").attr('disabled', true); }); });   No Match Test Test 2 Test 3   No Match Test Test 2 Test 3  

现场演示: http //jsfiddle.net/dZqEu/

 $('select').change(function() { var value = $(this).val(); $(this).siblings('select').children('option').each(function() { if ( $(this).val() === value ) { $(this).attr('disabled', true).siblings().removeAttr('disabled'); } }); }); 

您可能更喜欢此版本的代码:

 $('select').change(function() { $(this) .siblings('select') .children('option[value=' + this.value + ']') .attr('disabled', true) .siblings().removeAttr('disabled'); }); 

现场演示: http //jsfiddle.net/dZqEu/2/

请注意,第二个版本是一行代码(一行代码),但我将其格式化为更具可读性。 我更喜欢第二个版本。


另请注意,我的代码假定这两个SELECT框是DOM兄弟元素。 如果那不是你的情况,那么这段代码 – $(this).siblings('select') – 将不适合你,你将不得不使用jQuery的遍历方法跳转到另一个SELECT框。

在最坏的情况下 – 当SELECT框在DOM树中相距很远,并且遍历效率不高时 – 您可以只为它们分配ID属性并使用此代码选择另一个框:

 $('#select1, #select2').not(this) 

现场演示: http //jsfiddle.net/dZqEu/3/

试试这个:

 $(document).ready(function(){ $("select").change(function() { $("select").not(this).find("option[value="+ $(this).val() + "]").attr('disabled', true); }); }); 

如果您要启用以前禁用的选项(当从其他组合中取消选择该值时),请使用此增强版本:

 $(document).ready(function () { $("select").change(function () { var $this = $(this); var prevVal = $this.data("prev"); var otherSelects = $("select").not(this); otherSelects.find("option[value=" + $(this).val() + "]").attr('disabled', true); if (prevVal) { otherSelects.find("option[value=" + prevVal + "]").attr('disabled', false); } $this.data("prev", $this.val()); }); }); 

您的代码的问题在于,在change()例程中,您正在查看所有选择,而不是已更改并禁用所有选定条目的选择。 您需要找到所选条目的值,并在其他选择中禁用该值,而不是当前选项。

这样的东西可能有用[未经测试]:

 $(document).ready(function() { $("select").each(function(cSelect) { $(this).data('stored-value', $(this).val()); }); $("select").change(function() { var cSelected = $(this).val(); var cPrevious = $(this).data('stored-value'); $(this).data('stored-value', cSelected); var otherSelects = $("select").not(this); otherSelects.find('option[value=' + cPrevious + ']').removeAttr('disabled'); otherSelects.find('option[value=' + cSelected + ']').attr('disabled', 'disabled'); }); }); 

stored-value位使您知道在其他字段中启用哪些选项。

如果您有2个以上选择:

 $('select').on('change', function() { $('select option').removeAttr('disabled'); $('select').each(function(i, elt) { $('select').not(this).find('option[value="'+$(elt).val()+'"]').attr('disabled', true); }); });