gpt4 book ai didi

javascript - 防止两个具有相同选项的复选框出现重复选项

转载 作者:太空宇宙 更新时间:2023-11-04 14:18:52 25 4
gpt4 key购买 nike

我有 2 个选择框,我试图在这些选择框中避免重复值(选项)。它们都以相同的选项列表开始,但是在选择了 selectA 中的选项之后此选项不会出现在 selectB 中反之亦然。如果您选择 selectA-selectB-selectA,它应该可以工作... ETC。每次其中一个选择框应该有 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依此类推......最后你得到空列表。

有什么解决办法吗?

最佳答案

试试这个:fiddle

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

如果保持排序顺序很重要 fiddle with sort

关于javascript - 防止两个具有相同选项的复选框出现重复选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20099820/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com