Avoid duplication of choices on two checkboxes containing the same options

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?

Answer №1

Give this a shot: code example

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

If maintaining sort order is crucial, check out this sorted version

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Converting bullet point list to checkboxes once requirements have been satisfied

I am working on developing a password validator with specific regex conditions in Material UI that transitions from bullet points to checkboxes when the criteria are satisfied. https://i.sstatic.net/b0pgb.png Initially, I attempted to use the npm library ...

Displaying an error page instead of the error message when a backend or template engine error occurs

Whenever a template engine error occurs, it is displayed on the webpage. I am looking to implement a functionality where if our server is running in production mode, an error page will be shown instead of displaying our server's error directly. The m ...

Problem with exporting default class in Babel/Jest conflict

Currently, I am facing a challenge while testing the code using jest. The issue seems to be related to babel, especially regarding the export of a default class. Here is an example of the code causing the problem... export default class Test { get() { ...

Click event not triggering for selected option in jQuery dropdown menu

After adding dropdown anchor tags dynamically to the drop-down menu, the click event does not seem to be firing. Do I need to re-bind the click handler after using .append, or should I wrap the click handler in a function? <script src="https://code.jqu ...

How can an object inside an array be destructured in just one line?

Consider the following array: const array = [{b:2}] Can you extract the value of b using destructuring in just one line? I attempted something similar to this approach, but it did not yield the desired result: const [{b} = array] ...

Angular.js page failing to reflect changes following Firebase request completion

myApp.controller('RegistrationController', ['$scope', function($scope) { var auth = firebase.database().ref(); // console.log("auth::"+auth); $scope.login = function() { $scope.message = "Welcome " + $scope.user.ema ...

Passing the v-model property from a child component to a parent in VueJS

Consider a scenario where there is a Vue component structured like the following: Vue.component('child-comp',{ props:['name', 'val'], data: function(){ return { picked: '' } }, ...

Adding a proptype for a setState method in React components

I am currently developing a reusable component for a project. This particular component includes user and setUser as props, much like the example provided below. const UserComponent = ({ user, setUser }) => { const calcHandler = useCallback(() =& ...

Is it possible to achieve this flash effect using a more lightweight scripting approach?

My website currently has a flash header that can be found here. However, I have noticed that on older computers the flash file consumes a significant amount of resources, which is not ideal for user experience. Is there a way to achieve a similar effect ...

Color each row in PrimeVue DataTable based on the value of a specific column item

Recently, I came across a PrimeVue DataTable with a specific structure: <DataTable value="info"> <Column header="Name" field="name" /> <Column header="Desc." field="desc" /> <Colu ...

`Take action on a row by selecting the Edit option in CodeIgniter`

In my table, I have data displayed with an edit button in each row. What I want is for a pop-up or lightbox to appear when the edit button is clicked, without refreshing the page, and display all fields within that box. I am familiar with updating in the c ...

Enhancing Your Website with Multiple Background Images in CSS3

Having trouble understanding how to position multiple background images with CSS3. I'm struggling to get them to display at the top, middle, and bottom of the page. Can you help me figure out how to make an image appear at different positions using a ...

I've come across a challenge in my React PDF project where I am struggling to display the bottom and right margins, as well as the borders, in my reactPDF

I am currently working on creating a PDF using the @react-pdf/renderer library within my React project. Everything seems to be functioning correctly except for an issue with the right and bottom margins not appearing in the PDF. Strangely, the top and left ...

Inject HTML code containing a function that triggers upon button press

I am facing a challenge in inserting code through a submit button. Essentially, I am looking for this button to trigger a PHP function that adds a block of HTML code. Below is the function: function addTrainee(){ print_r('<form method="post&qu ...

Transforming a form submission into an AJAX post while already in an AJAX post

I am looking to convert a form submission to an ajax post request while working within the codeigniter framework. The current JavaScript code is: $('#book-appointment-submit').click(function(event) { event.preventDefault(); var formData ...

I'm encountering an issue with the MUI DateTimePicker where I'm getting a TypeError that says "value.isValid is not a function at Adapter

Having some trouble with the MUI DateTimePicker component from the @mui/x-date-pickers library when using Day.js as the date adapter. Every time I attempt to utilize the DateTimePicker with Day.js, I encounter the following error: value.isValid is not a ...

What steps should I take to fix my responsive media query?

I am currently working on fixing some responsive issues on my WordPress website. Previously, in mobile view, it looked like this: https://i.stack.imgur.com/vpvHy.jpg After adding the following code to the CSS of my child theme: @media only screen a ...

Can you explain the meaning behind this syntax?

Currently, I am utilizing Vuetify and I am in the process of getting the server-side controlled data tables up and running. While browsing through the documentation, I stumbled upon this code snippet here. However, I am facing some challenges in understan ...

Why is my custom Vuelidate validator not receiving the value from the component where it is being called?

On my registration page, I implemented a custom validator to ensure that the password meets specific criteria such as being at least 12 characters long and containing at least one digit. However, I encountered an issue where the custom validator was not r ...

There was an issue retrieving the value from the $.ajax() error function, as it returned [

After successfully receiving data from the input field and sending it to the database, everything seems to be working fine. However, when attempting to retrieve the data after sending it to the database, an error is encountered: [object HTMLInputElement]. ...