Eliminate a selected option from one dropdown menu that corresponds to another dropdown menu

I have been scouring the internet for a while now, but I still haven't found an answer. On my website, I have three dropdown menus.

These dropdowns are used for gathering user preferences so that users can control the output of results.

I am wondering if it is possible for a value to be removed from the other two dropdowns if it is selected in one.

For example, if the user selects "movies" in the first dropdown, it should not appear in the others.

Here are my dropdowns:

<select id="pref1select">
<option value="P">Preference One</option>
    <option value="M">Movie</option>
    <option value="T">Tv</option>
    <option value="G">Games</option>
</select>
<select id="pref2select">
<option value="P">Preference Two</option>
    <option value="M">Movie</option>
    <option value="T">Tv</option>
    <option value="G">Games</option>
</select>
<select id="pref3select">
<option value="P">Preference Three</option>
    <option value="M">Movie</option>
    <option value="T">Tv</option>
    <option value="G">Games</option>
</select>

Answer №1

Disabling the feature without removing it is possible.
Example: http://jsfiddle.net/p2SFA/1/

Modifying HTML by adding the .preferenceSelect class and using jQuery:

 $(document).ready(function() {
        $(".preferenceSelect").change(function() {
            // Get the selected value
            var selected = $("option:selected", $(this)).val();
            // Get the ID of this element
            var thisID = $(this).prop("id");
            // Reset so all values are showing:
            $(".preferenceSelect option").each(function() {
                $(this).prop("disabled", false);
            });
            $(".preferenceSelect").each(function() {
                if ($(this).prop("id") != thisID) {
                    $("option[value='" + selected + "']", $(this)).prop("disabled", true);
                }
            });

        });
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

<select id="pref1select" class="preferenceSelect">
    <option value="P">Preference One</option>
    <option value="M">Movie</option>
    <option value="T">Tv</option>
    <option value="G">Games</option>
</select>
<select id="pref2select" class="preferenceSelect">
    <option value="P">Preference Two</option>
    <option value="M">Movie</option>
    <option value="T">Tv</option>
    <option value="G">Games</option>
</select>
<select id="pref3select" class="preferenceSelect">
    <option value="P">Preference Three</option>
    <option value="M">Movie</option>
    <option value="T">Tv</option>
    <option value="G">Games</option>
</select>

If you wish to completely remove it, consider informing jQuery on what to add after resetting due to a new choice being made :)

Answer №2

Try using this code snippet for your specific needs:

$(document).ready(function() {
    $(".filter").change(function() {
        // Retrieve the selected value
        var choice = $("option:selected", $(this)).val();
        // Get the ID of the current element
        var elementID = $(this).attr("id");
        // Reset to display all values:
        $(".filter option").each(function() {
            $(this).show();
        });
        $(".filter").each(function() {
            if ($(this).attr("id") != elementID) {
                $("option[value='" + choice + "']", $(this)).hide();
            }
        });
    });
});`

Answer №3

Here's a helpful solution for you:

  $("select.preferenceSelect").on("change", function () {
            $("select.preferenceSelect option").prop("disabled", false);
            var selectedPref = $(this).find("option:selected").val();
            var selectId = $(this).attr("id");
            $("select.preferenceSelect option").each(function () {
                $(this).show();
            });
            $("select.preferenceSelect").each(function () {
                if ($(this).attr("id") != selectId) {
                    $(this).find("option[value='" + selectedPref + "']").prop("disabled", true);
                }
            });

        });

Give this a try and see how it works for you.

Answer №4

If you want to achieve a certain functionality based on the provided HTML, the following code snippet might help:

var $selects = $("select");

$selects.on("change", function(){
    var value = this.value;

    $("option[value='" + value +"']", $selects).prop("disabled", true);    
});

var $selects = $("select");

$selects.on("change", function(){
    var value = this.value;
    
    $("option[value='" + value +"']", $selects).prop("disabled", true);    
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select id="pref1select">
<option value="P">Preference One</option>
    <option value="M">Movie</option>
    <option value="T">Tv</option>
    <option value="G">Games</option>
</select>
<select id="pref2select">
<option value="P">Preference Two</option>
    <option value="M">Movie</option>
    <option value="T">Tv</option>
    <option value="G">Games</option>
</select>
<select id="pref3select">
<option value="P">Preference Three</option>
    <option value="M">Movie</option>
    <option value="T">Tv</option>
    <option value="G">Games</option>
</select>

This script disables duplicate options, but consider removing them completely for clarity. An issue arises as all "Preference #" options share the same value. I suggest using optgroup labels or eliminating values and keeping them disabled from the start since they shouldn't be clickable anyway. Learn more about option labels and separators here.

Sample Demo

Answer №5

Check out the following code snippet that works perfectly without any glitches. I've taken an approach where the selected option is disabled instead of being hidden from other dropdowns.

$( function() {
    course();
});

function course(){   
    var prevSelection;

    $(".primarySelect").on('focus', function () {
        prevSelection = this.value; 
    }).change(function() {
        var currentSelection = $("option:selected", $(this)).val();
        var selectionID = $(this).attr("id");

        $(".primarySelect option").each(function() {
            $(this).show();
        });

        $(".primarySelect").each(function() {
            var otherID=$(this).attr("id");
            if (otherID != selectionID) {
                if( $('#'+otherID).val() == currentSelection){ $('#'+otherID).val(''); } // needed for data review after form submission
                $("option[value='" + currentSelection + "']", $(this)).attr("disabled", true);
            }

            $("option[value='" + prevSelection + "']", $(this) ).attr("disabled", false); // reset previously selected option in all dropdowns

        });

        prevSelection =  $('#'+selectionID).val();
    });
}

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

Is it possible to utilize two :before pseudo classes within a single div element?

Suppose I had the following HTML code snippet: <div class="container"> <p>blah blah blah</p> </div> Can we apply two :before pseudo classes to that same container div? For example, like this: .container:before{ content: " "; ...

The package 'models' imported from is not found [ERR_MODULE_NOT_FOUND] error

I'm currently in the process of setting up my project to utilize absolute imports. To accomplish this, I've made adjustments to my jsconfig.json file as shown below: { "compilerOptions": { "baseUrl": "./src&quo ...

Perform an ajax request to a different domain

Is there a way to make an ajax call cross domain? Here is the script I currently have: $.ajax({ type: "GET", url: url, data: {sendername: sendername, email: email, subject: subject, message: message}, dataType: "jsonp", ...

Using Node.js to import modules without the need for assignment

In my recent project, I decided to organize my express application by putting all of my routes in a separate file named routes.js: module.exports = function(server) { // Server represents the Express object server.get('/something', (req, res) ...

Superfish - Adjust the Gap between each button

Is there a way to adjust the spacing between buttons on my superfish menu while using the vertical Menu CSS? ...

Prioritize returning AJAX data over iterating through the parent loop

Hey everyone, I'm having trouble wrapping my head around this issue even after researching various scenarios online. Here's what's going on: I have an array of strings named recipientsList. What I want to do is make an AJAX call for each s ...

The 'myCtrl' parameter is invalid as it is not recognized as a function and is currently set to undefined

I'm having trouble resolving this issue. I've implemented other controllers in the same manner that are working fine, but this specific one is throwing an error Error: ng:areq Bad Argument" "Argument 'myCtrl' is not a function, got un ...

Exploring Vue.Js and Airtable: Mastering the Art of Filtering

I am currently working on a project using vue.js to showcase information from an Airtable database. I am looking to implement a filtering functionality for the data displayed. The table contains education details, including subject information like biology ...

"Implementing a show/hide feature for a DIV based on a selected drop-down value using vanilla JavaScript (without any external libraries

I have different tide tables for various locations, each contained within its own div. The user can select a location from a dropdown menu, and when the page loads, it displays the tide table for the first location by default. Upon changing the location, o ...

What is the best way to interpret and execute conditions specified within strings like "condition1 and condition2"?

Received a JSON file from an external source with various conditions that need to be tested, either in real-time or through conversion. Imagine having an instance of a class called Person, with attributes {age: 13, country: "Norway"}, and an ext ...

Is there a way to incorporate a pixel stream within a React component?

Calling all developers experienced in customizing webpages with pixel streams - I need your help! After following Unreal's documentation on pixel streaming (), I successfully set up a pixel stream. I can modify the default stream page, but I'm s ...

Processing two Array Objects can be achieved without resorting to the EVAL function

I have two objects that I need to process. obj1 contains an array of objects with formulas. obj2 holds the values needed for the calculations. I am looking for a way to process and calculate both objects in order to obtain a result where the keys present ...

When clicking to open the md-select on Angular Material 1.1.0, an unwanted [object object] is being appended

Every time I try to open the md-select input, an [object Object] (string) is added to the body tag. Click here to see the md-select input After clicking the md-select once, this is how the body looks ...

Having trouble with the jQuery load function not functioning properly

I have encountered an issue with this code snippet while running it on XAMPP. The alert function is working fine, but the HTML content fails to load. I have included links to jQuery 3.2.1 for reference. index.html $(document).ready(function(){ $("#b ...

AngularJS: Error encountered when trying to assign a value to a read-only property in the ng-submit directive

I've been working on a personal project to practice angularJS, but I've encountered a problem that seems unsolvable to me. The issue arises when I try to utilize the submitLogin() function in my LoginCtrl.js file upon form submission. An error m ...

The functionality of the Kendo dropdown menu is experiencing issues on Internet Explorer 8

I've implemented the following code to connect a kendo dropdownlist: <input type="text" id="ddlCurrency" class="k-dropdown" name="currency" tabindex="3" style="width: 80px;" /> var ddlCurrency = $("#ddlCurrency").ken ...

What is the method to create an HTML div with a sloping edge?

my HTML & CSS code looks like this: https://i.sstatic.net/8vIaZ.jpg I would like it to look more like: https://i.sstatic.net/O9SA6.jpg Any tips on how I can achieve this?... ...

What was the recommended dimensions for CSS containers in 2018?

In the realm of responsive layout design, what is the recommended size for a max-width container as of 2018? My current choice is to use 1140px, which I find works well with the standard screen size of 1366px. ...

What is the benefit of using $q.all() with a single promise in AngularJS?

As I delve into this codebase, one snippet keeps popping up: $q.all([promise]).then(responseFunc); However, I find this confusing. After reading the documentation, I wonder why not simply use the following, as it's just a single promise... promise. ...

Is it possible to change label text using CSS without referencing the element by its ID?

Here is a simple code snippet: <div class="delem"><label class="required" for="last_name">Full Name :</label><input id="fullname" type="text" name="fullname" value="" class="fullsize" required=""></div> <div class="delem" ...