how to disable an option already selected in another <select>?

 ̄綄美尐妖づ 提交于 2019-12-05 14:25:56

If I understand you properly, this might be it:

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: example

Expanding on @IgorDymov's answer (credit should go to him), here's probably what I'd do (see fiddle):

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');

That way we completely refresh the selections each time a new one is made, which means properties become re-enabled again. You'll notice in the fiddle I reduced the number of selects and increased the number of options so that you don't get trapped in a situation where all options are disabled at the same time, I think that makes most sense.

A length example

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

Check Fiddle

To get the text in between the option tags of the currently selected option you would do this:

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

it translates to: get text of option with a value that is the same as the currently listed value in the select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!