jQuery Chosen: how to select 1 option value and remove the same one in another select-menu?

霸气de小男生 提交于 2019-12-03 06:33:43

Something like this should do it:

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");
});

I'm trying to use this code without the multiple choice so for each select only one option can be chosen. I want to use the allow_single_deselect: true code to remove an option if chosen in the select box but I can't get it working. I disabled the search option because I don't need it on this page.

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

});//]]></script>       

Since you are modifying the option which is selected in the first dropdown the previous options which were disabled are not enabled again.

You need to first enable all the options and then disable only the selected option. Try this

$('.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);
});

You set the disabled on every change, ofcourse it won't work...

In this code I change the disabled attribute based on the previous value;

<script>
$('.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)')
        .prop("disabled", function( i, val ) {
              return !val;
            });
});
</script>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!