jQuery Chosen:如何选择1个选项值并在另一个选择菜单中删除相同的值?

我把2个元素放在彼此旁边。 他们都使用jQuery Chosen插件。

这是代码:

1 2 3 4 5 6 1 2 3 4 5 6

这是Javascript。 jQuery库,最新的Chosen插件和CSS都包含在课程中。

  $('.chzn-select').trigger("liszt:updated"); $('.chzn-select').chosen().change( function() { var selectedValue = $(this).find('option:selected').val(); $(this).parent().find('option[value="'+ selectedValue +'"]:not(:selected)').attr('disabled','disabled'); });  

这是我想用上面的脚本完成的。

  • 有两个具有相同值的选择元素。 例如,当在元素1中选择值“1”时,我想在元素2中禁用它。
  • 然而。 在我取消选择元素1中的值“1”之后,它仍然在元素2中被禁用。这不是我想要的。 取消选择第一个元素中的值后,另一个值应该可用。

有谁知道如何做到这一点?

编辑

我现在在这里建立一个JSFiddle: http : //jsfiddle.net/dq97z/3/ 。 任何帮助将非常感激!

这样的事情应该这样做:

http://jsfiddle.net/musicisair/dq97z/10/

 // cache selects for use later var selects = $('.chzn-select'); // whenever the selection changes, either disable or enable the // option in the other selects selects.chosen().change(function() { var selected = []; // add all selected options to the array in the first loop selects.find("option").each(function() { if (this.selected) { selected[this.value] = this; } }) // then either disabled or enable them in the second loop: .each(function() { // if the current option is already selected in another select disable it. // otherwise, enable it. this.disabled = selected[this.value] && selected[this.value] !== this; }); // trigger the change in the "chosen" selects selects.trigger("liszt:updated"); }); 

我试图在没有多项选择的情况下使用此代码,因此对于每个选择,只能选择一个选项。 我想使用allow_single_deselect:true代码删除一个选项,如果在选择框中选择但我无法使其工作。 我禁用了搜索选项,因为我在此页面上不需要它。

  

由于您要修改在第一个下拉列表中选择的选项,因此不会再次启用先前禁用的选项。

您需要先启用所有选项,然后仅禁用所选选项。 试试这个

 $('.chzn-select').trigger("liszt:updated"); $('.chzn-select').chosen().change( function() { var selectedValue = $(this).find('option:selected').val(); var $options = $(this).parent().find('option').attr('disabled', false); $options.filter('option[value="'+ selectedValue +'"]:not(:selected)') .attr('disabled', true); }); 

你在每次改变时设置了禁用,当然它不起作用……

在此代码中,我根据以前的值更改disabled属性;