防止具有相同选项的两个复选框上的重复选项

Prevent duplicate option on two checkboxes with same options

本文关键字:选项 两个 复选框      更新时间:2023-09-26

我有 2 个选择框,我试图避免这些选择框中的值(选项(重复。它们都以相同的选项列表开始,但在selectA中选择选项后,此选项不会在selectB中看到,反之亦然。如果您选择selectA-selectB-selectA,它应该可以工作...等。每次其中一个选择框都应该带有 n-1 个选项。

我做了下一个..它有效,但在移动设备中.hide()它不起作用!

   $('#selectA').bind('change', function () {
            $("#selectB option").show();
            $("#selectB option[value='" + $(this + 'option:selected').attr('value') + "']").hide();
        });
    $('#selectB').bind('change', function () {
        $("#selectA option").show();
        alert($(this).find('option:selected').attr('value'));
        $("#selectA option[value='" + $(this).find('option:selected').attr('value') + "']").hide();
    });
}

尝试类:.hide()

.hide {display: none;}

  $('#selectA').bind('change', function () {
            $("#selectB option").removeClass('hide');
            $("#selectB option[value='" + $(this + 'option:selected').attr('value') + "']").addClass('hide');
        });
        $('#selectB').bind('change', function () {
            $("#selectA option").removeClass('hide');
            $("#selectA option[value='" + $(this).find('option:selected').attr('value') + "']").addClass('hide');
        });
    }

也不行。

试过这个:

    $('#selectA').on('change', function() {
        $('option:not(:selected)', this).clone().appendTo($('#selectB').empty());
    });
$('#selectB').on('change', function() {
        $('option:not(:selected)', this).clone().appendTo($('#selectA').empty());
    });

但这里的问题是,如果我们从 5 个选项开始,例如,在selectA中选择选项后,我将在 selectB 中得到 n-1,在选择选项后 selectB 我会在selectA得到 n-2 等等......最后你会得到空列表。

有什么想法如何解决吗?

试试这个: 小提琴

$(document).ready(function() {
    $('#selectA').on('change', function() { UpdateDropdown($(this), $('#selectB')); })
    $('#selectB').on('change', function() { UpdateDropdown($(this), $('#selectA')); })
    function UpdateDropdown($source, $target) {
        var $sourceitems = $('option:not(:selected)', $source).clone();
        var sourcevalues = $.map($sourceitems, function(option) { return option.value; });
        var $targetitem = $target.find(':selected');
        if ($.inArray($targetitem.val(), sourcevalues) == -1) {
           $sourceitems = $.merge($sourceitems, $targetitem);
        }
        $sourceitems.appendTo($target.empty());
    }
});

如果保持排序顺序很重要,请摆弄排序