Ensure that selected options are unique across multiple selections

Could you help me with a question that involves matching pairs of words in both Russian and English?

<div class="form-group" id="question4">
  <label for="q4FirstSelectEN">4</label>
    <div class="row">
      <div class="col-lg-offset-2 col-lg-2 q4EN">
        <select name="firstSelectEn" id="q4FirstSelectEN">
          <option disabled selected style="display: none" value=""></option>
          <option value="red">red</option>
          <option value="green">green</option>
          <option value="purple">purple</option>
        </select>
        <select class="top-buffer" name="secondSelectEn" id="q4SecondSelectEN">
          <option disabled selected style="display: none" value=""></option>
          <option value="red">red</option>
          <option value="green">green</option>
          <option value="purple">purple</option>
        </select>
        <select class="top-buffer" name="thirdSelectEn" id="q4ThirdSelectEN">
          <option disabled selected style="display: none" value=""></option>
          <option value="red">red</option>
          <option value="green">green</option>
          <option value="purple">purple</option>
        </select>
      </div>
      <div class="col-lg-2 q4RU">
        <select name="firstSelectRu" id="q4FirstSelectRu">
          <option disabled selected style="display: none" value=""></option>
          <option value="red">красный</option>
          <option value="green">зелёный</option>
          <option value="purple">фиолетовый</option>
        </select>
        <select  class="top-buffer" name="secondSelectRu" id="q4SecondSelectRu">
          <option disabled selected style="display: none" value=""></option>
          <option value="red">красный</option>
          <option value="green">зелёный</option>
          <option value="purple">фиолетовый</option>
        </select>
        <select  class="top-buffer" name="thirdSelectRu" id="q4ThirdSelectRU">
          <option disabled selected style="display: none" value=""></option>
          <option value="red">красный</option>
          <option value="green">зелёный</option>
          <option value="purple">фиолетовый</option>
        </select>
      </div>
    </div>
  </div>

When a user selects 'red' in the first (select) inside the (div class='q4EN'), all the remaining selects within this (div class=q4EN) will have the 'red' option become unselectable.

(The "nonSelectable" class in CSS sets display:none)

If the user changes their selection to 'green' instead of 'red' in the first (select), the 'red' option becomes available again in the rest of the selects, while 'green' becomes unselectable.

Once all three selects have been chosen, the user cannot make any more changes.

I've tried using JavaScript for this functionality, but it's not working as expected. Any ideas on how to fix it?

$(".q4EN").find("select").change(function () {
    $(".q4EN").find("select")
    .not(this)
    .find("option:selected")
    .addClass("nonSelectable");
});

Answer №1

It seems like the issue lies in the order of operations.

$(".q4EN").find("select").change(function () {
    $(".q4EN").find("select")   //Locates all select lists
    .not(this)                  //Excludes the one that was just changed
    .find("option:selected")    //Finds selected options in all except the one just changed
    .addClass("nonSelectable"); //Doesn't have any effect because no option was selected
});

You could try this approach:

    $(".q4EN").find("select").change(function() {UpdateOptions();});

    function UpdateOptions(){
        var ss = $(".q4EN").find("select");
        ss.find('option').prop("disabled", false); //Enables all options before disabling the selected ones
        ss.each(function () {
            var s = $(this).val();
            if(s != undefined && s != "") {
                ss.find("option[value=" + s + "]").prop("disabled", true);
            }
        });
    }

Answer №2

Here is an alternative method to accomplish your desired outcome. It involves iterating through each select element, finding the corresponding option, and disabling it.

$('select').find("option").addClass("selectable");

$('select').on("change",function()
{
   // $(this).find("option").prop("disabled",false); // uncomment this if you wish to reset the disabled selection
    var $thisId = this.id;
    var $selectedOption = $(this).find("option:selected").val();
    $('select').each(function()
    {
        if(this.id !== $thisId)
        {
          //  $(this).find("option").removeClass("non-selectable").addClass("selectable"); // uncomment this if you wish to reset the disabled selection
            $(this).find("option[value=" + $selectedOption + "]").prop("disabled",true).addClass("non-selectable").removeClass("selectable");

        }
    });    
})

https://fiddle.jshell.net/a2n234eq/4/

To target a specific group (such as EN and RU), simply change $('select') to $('.q4EN select')

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

Constructing a comprehensive inventory is a skill that requires strategy

Can someone advise on the best way to create a list structure with one parent category and two subcategories, each containing three items? Would it be ideal to use a combination of span and two uls, or perhaps a mix of span, anchor tags, and ul elements? ...

HTML list with clickable elements for querying the database and displaying the results in a <div> element

Patience please; I am a newcomer to StackOverflow and this is my inaugural question. Struggling with writing an effective algorithm, I wonder if my attempts to "push" it forward are causing me to complicate what should be a straightforward concept, or if i ...

VUE JS - My methods are triggering without any explicit invocation from my side

I've encountered a frustrating problem with Vue JS >.<. My methods are being triggered unexpectedly. I have a button that is supposed to execute a specific method, but this method gets executed along with other methods, causing annoyance... Her ...

Is it possible to use PHP to retrieve and display an entire webpage from a separate domain?

Currently, I am working on a PHP program that allows me to load a complete webpage and navigate the site while remaining in a different domain. However, I have encountered an issue with loading stylesheets and images due to them being relative links. I am ...

How can one address the issue of undefined data within table cells?

I have encountered an issue while reading and displaying an XML file on a webpage using a JavaScript script. The problem arises when the page loads, and the information inside the cells of the table shows as "UNDEFINED". The intended display should include ...

What is the best way to vertically align a label at a 270-degree angle?

I am trying to position text vertically at 270 degrees and in the middle of an image. This is my goal. Despite attempting to use the CSS 'transform' property, I have been unsuccessful. You can view the code I tried here. Below is the HTML and CS ...

Utilize the .not() filter function in JavaScript

I am trying to apply a filter of not(.pseudo-element) using JavaScript, but I am unsure how to add it. So far, I have been able to extract #app from the DOM with the following code: const app = document.getElementById('app') app.style.filter ...

Filtering DataGrid columns with an external button in Material-UI: A step-by-step guide

Imagine having a datagrid table structured as shown below: import * as React from 'react'; import { DataGrid, GridToolbar } from '@mui/x-data-grid'; import { useDemoData } from '@mui/x-data-grid-generator'; const VISIBLE_FIEL ...

Update the dropdown text when a user clicks on a dynamically added item within the list

Bootstrap 5. Here is my code snippet for the UL element, which will be populated dynamically from a database once the page is loaded. <div class="btn-group"> <button id="dropdownGerencia" class="btn btn-secondary bt ...

Encountering trouble with displaying data in Express and Mongoose

Struggling to comprehend how to define and utilize an API in Express, while using Mongoose to connect with MongoDB. Successfully saving objects from input on the front end, but getting lost when it comes to retrieving and displaying the saved data. Take a ...

What is the best way to adjust the height of the second column downwards?

I am trying to achieve a 2-column layout with both columns at the same height. This is how it currently appears: And this is how I want it to be: Here is my code snippet: html { background-color: lightblue; font-family: Tahoma, Geneva, sans-serif ...

Tips for contacting the giveaway host after the giveaway has finished

I am currently utilizing the Discord Giveaways module. I am interested in learning how to send a direct message to the host of the giveaway once it has ended. I haven't quite figured out how to do that yet. Here is what I have gathered so far: manag ...

Adjust the stacking order to remove focus from the text field

Currently, I am facing an issue with my search box not unfocusing when clicked. My goal is to have the search box lose focus when anything on the page is clicked, especially the background (div.bb). The elements positioned above the background are set to p ...

Increase the padding on Bootstrap 4 Sticky footer for a more polished look

While working on my Bootstrap 4 website hosted on Apache (Ubuntu Linux), I encountered an issue with the sticky footer. When there is only a small amount of content on the page, I have to scroll through excessive white space to reach the footer. I'm ...

Looking for a JavaScript function that can utilize AJAX to execute PHP code and display the PHP output on the webpage

I've been trying to use JavaScript to execute some PHP code and then display the results on the page. I came across a piece of code that achieves this using ajax and by placing the PHP code in an external file. However, the code I found seems to show ...

What is the best way to enable my search function to filter out specific items from a table?

Currently, I have created a table populated with data fetched from a JSON file. Now, my focus is on implementing a search functionality that filters out items based on user input and displays only those table rows matching the search criteria. The code sni ...

including a "continue" option to the jplayer interface

Does anyone know how to add a next button on jplayer? I've tried using the click function, but it doesn't seem to be working. The player is set up to use ajax to fetch songs and information about them. When one song ends, another is retrieved th ...

Adjust vertical dimension using rich text editor tag

I am currently using JSF with RichFaces version v.3.3.1.GA. I am trying to decrease the height style of the rich:editor tag (using TinyMCE), but for some reason it does not seem to be changing. <rich:editor id="transactionResult" style="height: 10px;" ...

When the redirect page includes a parameter, it has the ability to conceal the functionality of the subsequent page

I'm looking to redirect my page to another page while also triggering a hidden function on the next page. When I click on the redirect link, I want the page to redirect and for the function on the next page to be called as well. <script type="text ...

Encountered an issue while working with npm vue-cli

Operating System: Windows 10 Node Version: v8.9.2 NPM Version: 5.5.1 I successfully installed vue-cli using NPM, but encountered an error when trying to run 'npm run dev' command. Below is the error message: npm ERR! code ELIFECYCLE npm ERR! ...