Using JavaScript to enhance and highlight specific items in a dropdown menu

I am looking for a solution to prevent duplicate selections in multiple select dropdowns. I want to alert the user if they have chosen the same value in more than one dropdown. Should I assign different IDs to each dropdown or is it possible to use just one ID for all of them? The duplicated selection should be highlighted in red.

<form method="post" action="">
<select name="drop1" id="drop1" onchange="checkDropdowns()">
<option value=" " selected="selected"> </option>
...

My JavaScript function is as follows:

function checkDropdowns()
 {
  var iDropdowns = 4;
  var sValue;
  var sValue2;
for(var i = 1; i <= iDropdowns; ++i)
{
    sValue = document.getElementById('drop' + i).value;
    ...
} 
return true;
 }

I seem to be encountering an issue with my implementation. Any guidance or suggestions would be greatly appreciated.
For reference, here is my Fiddle

Answer №1

Alright, let's go with plan B this time. The previous attempt was filled with nonsense. This approach involves using an array to store used values and then checking if the next Select's value is in that array. Much simpler, right?

function validateDropdowns(){

var numOfDropdowns = 4,
    dropdownValue,
    usedValues = new Array();

for(var i = 1; i <= numOfDropdowns; i++)  {
    dropdownValue = document.getElementById('drop' + i).value;
    if (dropdownValue && usedValues.indexOf(dropdownValue) !== -1) {
        document.getElementById('drop' + i).style.backgroundColor="#cc0000";
    }
    else {
        usedValues.push(dropdownValue);
        document.getElementById('drop' + i).style.backgroundColor="#fff";
    }

} 
}

Answer №2

function checkDuplicates(element){
    var isDuplicate = false;
    document.querySelectorAll("select").forEach(function(selectElement){
        if (element != selectElement && element.value == selectElement.value){
            isDuplicate = true;
        }   
    });
    element.style.border  = isDuplicate ? "1px solid #f00" : "inherit";  
}

This is my recommended approach - make sure to include 'this' as a parameter in all your inline event calls.

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

Keep an ear out for updates on object changes in Angular

One of my challenges involves a form that directly updates an object in the following manner: component.html <input type="text" [(ngModel)]="user.name" /> <input type="text" [(ngModel)]="user.surname" /> <input type="text" [(ngModel)]="use ...

Is there a way to view Deno's transpiled JavaScript code while coding in TypeScript?

As I dive into Typescript with Deno, I am curious about how to view the JavaScript result. Are there any command line options that I may have overlooked in the documentation? P.S. I understand that Deno does not require a compilation step, but ultimately ...

Retrieve the element by clicking on its individual tooltip

I am currently struggling with a jQuery UI tooltip issue. Specifically, I would like to retrieve the element that the tooltip is associated with when clicking on it. My Approach So Far $(".sample").tooltip({ content: function () { return $(t ...

Create a compressed package of a Vue project that can easily be inserted into a Blogger blog post as a single HTML file

Is there a way to package all the files related to a Vue.js project (HTML, JavaScript, CSS) into one single HTML file for easy deployment on a Blogger Blogspot post? In the past, a question similar to this was asked regarding bundling files into a single ...

Add a variety of parameters to the URL in order to make an AJAX request

I want to dynamically add values from checked checkboxes to a URL for use in an AJAX call. I only want these values to be added to the URL if the checkbox is checked. If a user checks and then unchecks, I do not want that value included in the URL. Below ...

Is it possible to modify the sub/child divs within a draggable parent div and assign them a different class?

Greetings, after being a long-time reader, I have finally decided to post for the first time. In the process of creating a webpage with jQuery drag and drop divs, I am curious about how to change the class of a child div within a draggable div once it is d ...

Instructions for activating and deactivating a numerical input field with a checkbox

Is there a way to create a pair of a checkbox and number field that are linked together? When the checkbox is clicked, it should disable the associated number field. Javascript File: $(document).ready(function(){ $("input[name=check]").click(function(){ ...

Create your own AngularJS directive for displaying or hiding elements using ng-show/ng

Caution: Angular rookie in action. I'm attempting to craft a personalized widget that initially displays a "Reply" link, and upon clicking it, should hide the link and reveal a textarea. Here's my current progress, but unfortunately, it's n ...

Executing a javascript function from PHP when a form is submitted: a comprehensive guide

I am looking to trigger a javascript function from PHP when the form is submitted. This function will have access to PHP variables and will use AJAX to send them to a PHP script on another website. The code below serves as an example: <?php .... ..... ...

jQuery DatePicker Not Displaying Calendar

I've been attempting to implement a date picker in jQuery. I've included the necessary code within the head tag: <link rel="stylesheet" type="text/css" media="screen" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jqu ...

What is the best way to cycle through a nested JS object?

I am currently utilizing useState and axios to make an API call, retrieve the response, and pass it to a Component for rendering. const [state,setState] = useState([]); const getCurrData = () => { axios.get('working api endpoint url').then(r ...

Guide to transforming an embed/nested FormGroup into FormData

Presenting my Form Group: this.storeGroup = this.fb.group({ _user: [''], name: ['', Validators.compose([Validators.required, Validators.maxLength(60)])], url_name: [''], desc: ['', Validators.compose([Valida ...

Issue with triggering (keyup.enter) in Angular 8 for readonly HTML input elements

My goal is to execute a function when the user presses Enter. By setting this input as readonly, my intention is to prevent the user from changing the value once it has been entered. The value will be populated from a popup triggered by the click attribut ...

Vue.js fails to display multiple uploaded images

I have been working on implementing a multiple image upload feature using vue.js. So far, everything seems to be functioning correctly. However, I am facing an issue where the HTML does not display thumbnails of the images I have selected. Additionally, I ...

Updating an Angular directive with dynamically added ng-module and ng-change attributes

Can someone check if I'm on the right track? Preamble: I've created a Typeahead class that fetches data and keeps it within itself. The class has the following structure: input: stores the search text. list: stores the results. change: a funct ...

Using jQuery to access the ID of a div and create a custom close button

I am trying to implement a close button for my popup DIVs. Each one has a unique ID and I want to hide them by setting the CSS 'display' property to 'none' when closed. However, the following example is not functioning as expected. I a ...

Firebase onCall function is executing properly, however, it is only delivering {data: null} as the

I am facing an issue with my cloud function where everything runs smoothly until I attempt to return a response back to the front-end. Despite successfully modifying databases, the final log points D and G still show {data:null} as the output. I have a fe ...

Unable to assign values to textarea and checkbox in MVC5

I am currently facing an issue with setting values in JavaScript + jQuery in MVC 5 for textareas and checkboxes. Here is the JavaScript code I am using: document.getElementById("UpdatetxtDescription").value = "abc"; document.getElementById("Upda ...

I am attempting to establish a connection with the Converge Pro 2 system from Clearone using NodeJS node-telnet-client, but unfortunately, my efforts to connect have been unsuccessful

My connection settings are as follows: { host: '192.168.10.28', port: 23, shellPrompt: '=>', timeout: 1500, loginPrompt: '/Username[: ]*$/i', passwordPrompt: '/Password: /i', username: 'clearone ...

Strategies for resolving minor validation challenges (Almost complete, just a few finishing touches needed ...)

This question was originally posted in Spanish on es.stackoverflow.com by Julian Dumitrel: I had planned to make a record, step by step, where I had 3 different steps all within one <form>. After finishing my form validator successfully, I encounte ...