I have two select boxes where I am trying to prevent duplicated values (options) in each select box. Both select boxes start with the same options list, but once an option is selected in selectA
, it should no longer be visible in selectB
, and vice versa. This functionality should work seamlessly even if you switch between selecting options in selectA
and selectB
multiple times. Each select box should always have n-1 options available.
I have implemented the following code, which works fine, but I've noticed that it does not work correctly on mobile devices due to the use of .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();
});
}
I also attempted to use class-based hiding, but that did not work either.
.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');
});
}
Still, no luck.
Another approach I tried was as follows:
$('#selectA').on('change', function() {
$('option:not(:selected)', this).clone().appendTo($('#selectB').empty());
});
$('#selectB').on('change', function() {
$('option:not(:selected)', this).clone().appendTo($('#selectA').empty());
});
However, this method led to the issue of depleting the options list entirely after sequential selections, starting with 5 options.
Do you have any ideas or suggestions on how to resolve this issue?