Using JavaScript, populate a <select> menu with multiple <option> elements generated from an object

I am working on creating a form that includes two select elements. The second select's options should change based on the choice made in the first one.

For example, if value 1 is selected in select 1 => Display object 1 as options in select 2.

Below is the JavaScript code I have written:

var EntiteGenerale = document.getElementById("TypeEntityId").value;
var select = document.getElementById("EntityId");
var index;

var Departement = {
  1: "Finances et Administration",
  2: "Service Logistique Transversale",
  // Remaining Department objects...
};

var CentreSecours = {
  1: "CG BUTGENBACH BULLINGEN",
  2: "CS BLEGNY",
  // Remaining Centre Secours objects...
}; 

function DisplayEntiteL() {
  if (EntiteGenerale === 2) {
    for (index in Departement) {
      select.options[select.options.length] = new Option(Departement[index], index);
    }
  } else if (EntiteGenerale === 3) {
    for (index in CentreSecours) {
      select.options[select.options.length] = new Option(CentreSecours[index], index);
    }
  } else {
    console.log("Nothing to display");
  }
}

However, when testing the functionality of the code, the "Nothing to display" message is always shown because the options are not being added correctly.

Could someone please review my code and let me know what might be wrong? You can view the full code on this JSFiddle link.

Thank you for your assistance.

Kind regards,

Answer №1

If I grasp your inquiry correctly, you aim to have the <option> elements within the EntityId select change dynamically based on the value of the TypeEntityId select element. It's recommended to modify your code by adding the change event to the TypeEntityId select using the addEventListener() method:

/* Bind change event via addEventListener() */
document.getElementById("TypeEntityId").addEventListener('change', DisplayEntiteL)

Furthermore, adjust your if conditions so that the values in the comparisons are strings for fulfilling the value matching conditions:

/* Add event parameter to localize value extraction from corresponding
select element */
function DisplayEntiteL(event) {

  /* Obtain current value of TypeEntityId select */
  const value = event.currentTarget.value;
  const entityId = document.getElementById("EntityId");

  /* Clear any previous options from EntityId select */
  while (entityId.hasChildNodes()) {
    entityId.removeChild(entityId.lastChild);
  }

    /* If the value of TypeEntityId is '2', display Departement items in
  entityId select */
  if (value === '2') {
    for (index in Departement) {
      entityId.appendChild(new Option(Departement[index], index));
    }

  }   
    /* If the value of TypeEntityId is '3', show CentreSecours items in
  entityId select */
  else if (value === '3') {

    for (index in CentreSecours) {
      entityId.appendChild(new Option(CentreSecours[index], index));
    }
  } 
  /* Otherwise, log a message to the console */
  else {
    /* entityId.appendChild(new Option('No options')); */
    console.log("rien à afficher");
  }
}

The above code snippet also introduces the event parameter, enabling access to the value of the TypeEntityId select within the event handler. For a fully functional example, refer to this JSFiddle link, or take a look at the provided sample below:

...

Answer №2

  1. Ensure to store the selected value before executing the change function in order to maintain consistency.
  2. Call the function inside the change event handler for accuracy.
  3. Remember to convert the selected value to an integer from a string to avoid === returning false, as it validates datatype as well.

var EntiteGenerale = document.getElementById("TypeEntityId");
var select = document.getElementById("EntityId");
var index;

var Departement = {
  1: "Finances et Administration",
  2: "Service Logistique Transversale",
  3: "Institut de Formation",
  4: "Communication, Marketing & Commercial",
  5: "Volontariat",
  6: "Ressources Humaines",
  7: "Service francophone du sang",
  8: "Service ECM et DIH",
  9: "Service Tracing",
  10: "Département Secours"
};

var CentreSecours = {
  1: "CG BUTGENBACH BULLINGEN",
  2: "CS BLEGNY",
  3: "CS BRABANT OUEST",
  4: "CS CHARLEROI",
  5: "CS HAUTE SENNE",
  6: "CS HERSTAL - OUPEYE",
  7: "CS TOURNAI",
  8: "CS NAMUR",
  9: "CS OTTIGNIES",
  10: "CS OUGREE",
  11: "CS PHILIPPEVILLE",
  12: "CS ROCHEFORT",
  13: "CS SPA",
  14: "CS HESBAYE-CONDROZ",
  15: "CS JODOIGNE",
  16: "CS LIEGE",
  17: "CS LUXEMBOURG",
  18: "CS MONS",
  19: "CS MOUSCRON"
};
function DisplayEntiteL() {
  EntiteGenerale = parseFloat(EntiteGenerale.value);
  if (EntiteGenerale === 2) {
    for (index in Departement) {
      select.options[select.options.length] = new Option(Departement[index], index);
    }
  } else if (EntiteGenerale === 3) {
    for (index in CentreSecours) {
      select.options[select.options.length] = new Option(CentreSecours[index], index);
    }
  } else {
    console.log("rien à afficher");
  }
}
input[type='checkbox'] {
  -webkit-appearance: none;
  -moz-appearance: none;
  -o-appearance: none;
  border: 1px solid rgba(0, 0, 0, 0.1);
  width: 15px;
  height: 15px;
  -webkit-border-radius: 3px;
  -moz-border-radius: 3px;
  border-radius: 3px;
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
  -webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s;
  -o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
  transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
}

input[type='radio'] {
  -webkit-appearance: none;
  -moz-appearance: none;
  -o-appearance: none;
  border: 1px solid rgba(0, 0, 0, 0.1);
  width: 15px;
  height: 15px;
  -webkit-border-radius: 3px;
  -moz-border-radius: 3px;
  border-radius: 3px;
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
  -webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s;
  -o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
  transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
}

input[type='radio']:checked {
  background-color: red;
}

input[type='checkbox']:checked {
  background-color: red;
}

input::placeholder {
  font-size: 0.7rem;
}

select {
  border-radius: 20px;
  font-size: 0.8rem;
}

select:focus {
  border-color: #ff2400;
  outline: 0;
  box-shadow: none;
}
<div class="row col-md-12">
  <div class="col-md-12">
    Votre entité générale :&nbsp;&nbsp;
    <select onchange="DisplayEntiteL()" data-val="true" data-val-number="The field TypeEntityId must be a number." data-val-range="The field TypeEntityId must be between 1 and 2147483647." data-val-range-max="2147483647" data-val-range-min="1" data-val-required="Vous devez donner un TYPE d'entité"
      id="TypeEntityId" name="TypeEntityId">
      &e [...]

Find out why parseFloat is crucial:

https://i.sstatic.net/DVkhL.png

Answer №3

Big thanks to @prasanth!

After conducting further research, I experimented with a new approach that worked flawlessly. I implemented a function to reset the select element before populating it with new data.

  <select onchange="DisplayEntiteL(event)"></select>

--

 var EntiteGenerale = document.getElementById("TypeEntityId");
    var select = document.getElementById("EntityId");
    var index;

    var Departement = {
      1: "Finances et Administration",
      2: "Service Logistique Transversale",
      3: "Institut de Formation",
      // more department entries...
    };

    var CentreSecours = {
      1: "CG BUTGENBACH BULLINGEN",
      2: "CS BLEGNY",
      3: "CS BRABANT OUEST",
      // more center entries...
    };


    function clearOption(){
      var x = document.getElementById("EntityId");
      while (x.length != 0) {
        x.remove(x.length-1);
      }
     }

    function DisplayEntiteL(event) {
      if (event.target.value === '1') {
        clearOption();
        for (index in Departement) {
          select.options[select.options.length] = new Option(Departement[index], index);
        }
      } else if (event.target.value === '2') {
        clearOption();
        for (index in CentreSecours) {
          select.options[select.options.length] = new Option(CentreSecours[index], index);
        }
      } else {
        console.log("No data to display");
      }
    }

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

Utilizing JavaScript Event Listener to Identify the Relevant PHP File for Display

I have incorporated two separate PHP files in my code: tabs.php accordion.php Both files iterate through the same dataset, but present the information in different ways. The choice between displaying tabs or accordions depends on the user's screen s ...

Retrieve coordinates, specifically latitude and longitude, by utilizing AJAX and JSONP

Trying to obtain latitude and longitude using AJAX JSONP. Here is the code snippet: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script> <script> $(document).ready(function(){ var ...

Issue with process.env.NODE_ENV not functioning appropriately in NodeJS when utilizing package.json scripts

I currently have three separate databases configured for testing, development, and production purposes. My goal now is to make my express app switch between these databases based on the script that is being executed. These are the scripts I am using: "s ...

Trouble with launching Semantic UI modal

I have implemented a button using Semantic UI and set up a click event to open a modal when clicked, but nothing is happening. When I click on the link, there is no response. I'm unsure what the issue might be. Below is the code for the button: < ...

Can we accurately pinpoint individual LineSegments in three.js by hovering over them, especially those with unique geometries?

Creating two examples of drawing lines in three.js was quite a fun challenge. One example showcased different geometry and material, while the other kept it simple with just one geometry and material. The demonstration links can be found here: Example 1 an ...

THREE.js - Attempting to find the closest point (Vector 3) on an object based on a Vector 3 created from a mouse

As I work on developing a point-and-click test game, I've made significant progress by conducting thorough research and finding answers to various inquiries on Stack Overflow. However, I have encountered an issue that I can't seem to find any exi ...

The property is returning an empty string, but the function is functioning perfectly

Check out this related Stack Overflow post exports.getAddress = asyncHandler(async (req, res, next) => { var lon = req.query.lon; var lat = req.query.lat; var formattedAddress = ""; var url1 = 'url' request(url1 ...

The Fusion of Ember.js and Socket.io: Revolutionizing Web

I have been trying to incorporate a basic Ember application into the view of my node application. I have verified that Ember is properly set up and my sockets are functioning correctly. However, I am encountering an issue where the data is not being displa ...

Remove the class upon clicking

I recently created a toggle-menu for my website that includes some cool effects on the hamburger menu icon. The issue I am facing is that I added a JavaScript function to add a "close" class when clicking on the menu icon, transforming it into an "X". Whil ...

Utilize a generic data type for a property that can accept values of type 'number', 'string', or 'undefined'

This query involves React code but pertains to typescript rather than react. To simplify, I have a component called MyList which accepts a single generic type argument passed to the props type. The generic type represents an object that will be used to c ...

Connect the front end files, including HTML, CSS, and JavaScript, to the Node.js backend

I'm a beginner in web development and recently completed an online course on node.js and express. However, the course didn't cover how to add HTML, CSS, and JS files when using Node. I attempted the following: var express = require('expres ...

Using JavaScript and Regular Expressions for Performing Multiple Replacements

One issue that arises is that although the replacement functions as expected, all occurrences are replaced with the first find. (For example, see code below). The variable target represents the input field that contains the string to be highlighted, while ...

Dealing with Exceptions in NestJS and TypeORM: Troubleshooting "Get Status is not a function"

Currently, I am working on an application utilizing NestJS and TypeORM. My main objective is to handle TypeORM errors by using exception filters. However, I have run into a roadblock as I am facing this particular error: (node:345) UnhandledPromiseReject ...

Encountering a deadly mistake with LNK1181 while attempting to npm install web3

On my Windows system, I attempted to install the web3 node package using npm install. I followed the necessary steps by first installing Windows build tools: npm install --global --production windows-build-tools This command executed without issues, but ...

There seems to be an issue with the pastebin api createPasteFromFile method as it is showing an error of 'create

I'm currently working on a logging system using node for a twitch chat. The idea is that when you type "!logs user" in the chat, it should upload the corresponding user.txt file to pastebin and provide a link to it in the chat. For this project, I am ...

Ways to delete a property from an element that was originally included with jquery

On my jsp page, I am implementing a jQuery autocomplete feature for a text field with the id "mytextfield". jQuery(function(){ $("#mytextfield").autocomplete("popuppages/listall.jsp"); }); Sometimes, based on user input and pr ...

Adding elements to the DOM with JavaScript and inheriting event handlers

In my web application, I have set up a form with a textarea and a button. Upon submission, I prevent the default action using e.preventDefault() and submit the form via AJAX. The returned query is then prepended as information inside a div at the top of a ...

Patience is key as we await the arrival of the loaded data before making a return in AngularFire 0

I am working on a form that should only be submitted if the user provides a valid access key ($scope.access_key) - and each key can only be used once. Within my controller, I have the following method: $scope.verifyAccess = function() { var ref = new ...

Is there a way in React JS to attempt a function multiple times using try/catch?

I wrote a function with try catch inside where I make a call to an API for a response. The response returns a Result object with some data. Occasionally, I need to retry the function if certain conditions are met, such as having no name but having a bundle ...

Type of Angular Service Issue: string or null

I'm encountering a persistent issue with my Angular code, specifically while calling services in my application built on Angular 13. The problem arises when trying to access the user API from the backend, leading to recurrent errors. Despite extensive ...