Exclude choices from dropdown menu if they have already been chosen in another option

I need help with a form that allows users to add additional states and text boxes for each added state. The goal is to prevent users from selecting the same state in multiple select boxes.

<form action=state.php method=post> 

<a href="javascript:addElement();" style='color:blue; text-decoration:underline;'>Add a State </a> &nbsp; &nbsp; 
<a href='javascript:removeElement();' style='color:blue; text-decoration:underline;' >Remove </a><br /><br />

<script type="text/javascript">
    var intTextBox=0;

    //FUNCTION TO ADD TEXT BOX ELEMENT
    function addElement() {
        intTextBox = intTextBox + 1;
        var contentID = document.getElementById('addresscontent');

        var newTBDiv = document.createElement('div');

        newTBDiv.setAttribute('id','strText'+intTextBox);

        newTBDiv.innerHTML = "<select   id='u" + intTextBox + "' name=b_state[" + intTextBox + "][statename]/><option value=''>Select a State</option><option  value='AK'>AK</option><option  value='AL'>AL</option><option  value='AR'>AR</option><option  value='AS'>AS</option><option  value='AZ'>AZ</option><option  value='CA'>CA</option></select> &nbsp; <span style='font-size:12px;'>URL (if different) </span><input style='border:1px solid black; ' size=60 type='text' id='u" + intTextBox + "' name=b__state[" +intTextBox + "][url] /><br>";

        contentID.appendChild(newTBDiv);
    }

    //FUNCTION TO REMOVE TEXT BOX ELEMENT
    function removeElement()  {
        if(intTextBox != 0)  {
            var contentID = document.getElementById('addresscontent');
            contentID.removeChild(document.getElementById('strText'+intTextBox));
            intTextBox = intTextBox-1;
        }
    }
</script>

<div id="addresscontent"></div>

</div>

<input type=submit value='go'>

Answer №1

Follow these instructions to achieve the desired outcome:

1) Identify and gather all relevant select fields by accessing them through a node list: document.getElementById("myBigForm").getElementsByTagName("select");

2) Proceed to iterate through each select field, then within each field, iterate through the option elements.

3) If a certain value is detected in an option element, remove that child from its parent.

var filterOptions = function (targetValue) {
        "use strict";
        var selectsList = document.getElementById("myBigForm").getElementsByTagName("select"),
            totalSelects = selectsList.length,
            indexSelects = 0,
            currentOptions = [],
            totalOptions = 0,
            indexOptions = 0;
        for (indexSelects = 0; indexSelects < totalSelects; indexSelects += 1) {
            currentOptions = selectsList[indexSelects].getElementsByTagName("option");
            totalOptions = currentOptions.length;
            for (indexOptions = 0; indexOptions < totalOptions; indexOptions += 1) {
                if (currentOptions[indexOptions].value === targetValue) {
                    selectsList[indexSelects].removeChild(currentOptions[indexOptions]);
                    break;
                }
            }
        }
    };

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

Axios encounters CORS issues, while fetch operates smoothly

After going through various questions on CORS errors to no avail, I am facing a dilemma in my NuxtJS client application. Whenever I try to make a simple POST request using axios, I encounter CORS issues. However, when I switch to using the fetch API, every ...

Vue.js is not incrementing the counter as expected

I've encountered an issue with a button that has a click event to increment data value by 5, but instead of adding 5 it is appended by 5. Click here for the code example <div id="react"> <button @click='counter += 5'>Increment& ...

The functionality of displaying specific divs when multiple checkboxes are selected is currently experiencing technical issues

Within my setup, I have a selection segment which includes seven checkboxes for each day of the week: Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, and Saturday. Additionally, there are two other sections featuring more checkbox options: Morning Se ...

Issues with displaying success or error messages when submitting a form

I am currently working on a php/ajax/javascript form and I'm seeking assistance from John Fable to troubleshoot an issue. Specifically, I need help with displaying the success and error messages correctly. You can follow our discussion on this topic a ...

AngularJS failing to display HTML content is a common issue encountered

I am a beginner in Angular JS and recently wrote a simple Angular code. However, I am encountering issues with the HTML rendering incorrectly or the expressions not getting evaluated. I could use some help identifying what I might be missing. The version ...

Console displaying message of comfort twice - ReactJS

I have a simple app that increments the count from 10 to 11 in the componentDidMount life cycle, but for some reason, the numbers 10 and 11 are appearing twice in the console. I would like to understand why this is happening. Here is the code snippet: im ...

The function 'ChartModule' cannot be called, as function calls are not supported

I am encountering a similar problem as discussed in Angular 2 - AOT - Calling function 'ChartModule', function calls not supported ERROR: Error encountered while resolving symbol values statically. Trying to call function 'ChartModule&apos ...

Tips for deleting multiple objects from an array in angular version 13

I am facing an issue where I am trying to delete multiple objects from an array by selecting the checkbox on a table row. However, I am only able to delete one item at a time. How can I resolve this problem and successfully delete multiple selected objects ...

Option list malfunctioning in Safari, Mozilla, as well as Chrome browsers

I encountered some issues while working on the front-end of my web app. Here are a few problems: I need to truncate text if it's too long, so I use the following CSS: .suggestion-box-text { white-space: nowrap; overflow: hidden; text-overfl ...

I am encountering an issue where the key is not located in the response array in PHP, causing my JavaScript chart to remain

Hey there! I'm currently working on a school project and could really use some assistance. The task at hand involves creating a web interface that can interact with an endpoint in order to: - Authenticate a registered user to retrieve an authenticati ...

Placing a MongoDB query results in an increase of roughly 120MB in the total JS heap size

I'm puzzled by the fact that the heap size increases when I include a MongoDB database query in a function within my controller. Here is the code for my router: import { Router } from "express"; import profileController from '../contro ...

Error: Trying to access a property that is undefined (specifically referencing 'rendered') has resulted in an uncaught TypeError

As a newcomer to React, I'm attempting to create a headless WordPress application. However, when I fetch a post, I only receive the first value. After fetching the post, I save it in the state: componentDidMount() { this.setState({ lo ...

What are the steps to initiate mongodb within this particular application?

Recently, I received an assignment from this company to integrate MongoDB into a Node.js application. Since I haven't worked with MongoDB before, I'm unsure how to establish a connection with the database in the application. My main goal is to su ...

Guide on creating a cookie verification process with no contents

Request for Assistance: let cartHelper = { cartCookieName: "_cart", getCart: function (callback = undefined) { return apiHelper.getRequest( "/carts", (response) => { documen ...

What is the best way to verify that a check should have various attributes using chai-things?

Searching for a way to verify if an array in my mocha tests consists of an Object in my Node.js application, I discovered that with Chai-Things, I can use: [{ pet: 'cat' }, { pet: 'dog' }].should.include({ pet: 'cat' }) or ...

Incorporate a Web Worker into your webpack library for enhanced performance

I am facing an issue while attempting to include a web worker in my custom npm package. [App] -> [my npm package -> load worker] Within the npm package, I am utilizing worker-loader to import the worker file: import Worker from 'worker-loader! ...

Update the page with AJAX-loaded content

I am currently utilizing a .load() script to update the content on a webpage in order to navigate through the site. This is resulting in URLs such as: www.123.com/front/#index www.123.com/front/#about www.123.com/front/#contact However, I am encountering ...

Automatically reload a particular webpage upon closing a pop-up window (using jQuery)

I am facing an issue with a pop-up named PopUp1 on page0.aspx. The problem occurs when a user clicks on a row in the GridView within PopUp1, causing another pop-up to launch, loading my page1.aspx. The complication arises when the user navigates through l ...

Applying a condition to filter elements using AngularJS

I have created an array in my controller with the following data: var people = [ { name:"Alice", number:'808574629632', email:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail ...

What is the best way to show a progress bar while waiting for an entire aspx page to finish

Is there a way to display a progress bar on my default.aspx page until the entire page is loaded? I currently have a master page called Root.master. I attempted to use the following code: <html> <head><title>xx</title> </head&g ...