Creating a single loop in Javascript to populate two dropdown menus with options

Is there a way to populate two dropdown menus in JavaScript with numbers using the same for loop? Currently, only one is being populated, specifically the last one.

for (var i=1; i<10; i++)
{
   var option = document.createElement("option");
   option.text = i; 
   option.value = i;        
   document.getElementById('first').options.add(option);
   document.getElementById('second').options.add(option);               
}

It seems that 'second' gets populated while 'first' does not. If I switch the order of 'second' and 'first', then 'first' gets populated instead.

Is there a way to achieve this without having to use two separate for loops? I have tried passing the ID via a function but still end up with the same result.

Any suggestions would be greatly appreciated. Thank you.

Answer №1

Small tweak in your code snippet

for (let j=0; j<10; j++)
{
   let element = document.createElement("element");
   element.text = j;
   element.value = j;   
   let newElement = element.cloneNode(true);   

   document.getElementById('primary').elements.add(element);
   document.getElementById('secondary').elements.add(newElement);               
}

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

Angular, choose, establish a default option

Despite my attempts, I am struggling to set the default option for a select element using AngularJS. My Technologies: AngularJS, Angular-UI-router, Bootstrap Key HTML snippet: <select ng-model="selectedCompany" ng-options="c.name for c in companies" ...

The PDF format is experiencing compatibility issues when used with the CSS property for page breaks after:

My PDF with CSS page breaks is not functioning properly, as the pages are not breaking as intended. Removing position:absolute solves the issue but leaves space after each page. I suspect it may be a CSS problem, but I'm unsure. If the issue lies wit ...

JavaScript - Error encountered when accessing information from elements in the DOM

Just started learning javascript and encountering a problem that I can't seem to solve. I'm attempting to assign the className of a <div> element to a variable, but I keep receiving this error message: scripts.js:30 Uncaught TypeError: Can ...

The perplexing behavior of RxJS Observables with Mongo Cursors

Recently, I've been working on converting a mongo cursor into an observable using my own RxJS implementation. Despite finding numerous solutions online, I wanted to challenge myself by creating one from scratch. I would greatly appreciate it if someo ...

Failure of AJAX to transmit variable to PHP script

I am relatively new to PHP and currently working on the dashboard page of a website where an administrator can view all existing admins. Each admin's row has a button that is supposed to check their privileges, such as access to article editing and cl ...

The text loader feature in THREE.js is failing to load

My first attempt at coding THREE.js resulted in a black screen when I tried to load the Text loader. Can someone help me resolve this issue? I kept getting the following error even after multiple attempts: three.module.js:38595 GET 404 (Not Found) ...

Issue encountered during the process of importing Excel information utilizing the xlsx library

Currently, I am attempting to incorporate excel data into my angular application using the following library: xlsx However, upon downloading the project and attempting to run it locally, I encountered an error when trying to upload the excel file: Uncau ...

The left and right arrows maintain their visibility even when they are outside of the image

I am a beginner in the world of web development and I am trying to implement left and right navigation for images using arrows. My goal is to have the arrows fade in when the mouse hovers over the image and fade out when it's moved away. However, I am ...

Adding hue to the portion of text following a JavaScript split() operation

I need assistance in printing the text entered in a textarea with different colors. I am separating the string using the split() method, which works fine. However, I now want to print the substrings in the textarea with colors. How can this be achieved? & ...

The Importance of Selenium Events and Patience

Currently, I am using Selenium to automate some testing for our company's website, but encountering issues along the way. TestItemFromSearch: (driver, part, qty) => { Search.SearchItem(driver, part); driver.findElement(By.id('enterQty ...

Executing a function in ExpressJS at regular intervals of 24 hours

Can someone share the most effective method to schedule an automated task every 24 hours in ExpressJS? I have thoroughly researched possible solutions but haven't found any option other than using an infinite loop. Is there only one way to achieve th ...

How to dynamically populate a select option with data from a database in CodeIgniter 3 and automatically display the result in a text

How can I fetch select options from a database in CodeIgniter 3 and display the result in a text field and span area? Currently, I am only able to display data from the row_name when an option is selected. Here is my current implementation: <?php $query ...

Is it advisable to send an object as an argument in a function?

Here's the code snippet I'm working with: const failure1 = false; const failure2 = false; function callbackFunction(callback, errorCallback) { if (failure1) { errorCallback({ name: 'Negative event1 occurred', ...

Is there a way to update a JSON file using React?

I'm looking for a solution to update a JSON file in React. Is it possible? Below is the code snippet that executes when an HTML element is clicked. Ultimately, it invokes VoteTracking, the function responsible for updating the JSON file. handleC ...

Tips for obtaining the identifier of a div element while employing the bind() function in jQuery

Imagine having the following div. <div id="456" class="xyz">Lorem Ipsum</div> If I want to execute a function when this specific div is hovered over, I can achieve it like this: $(".xyz").bind({ mouseenter : AnotherFunction(id) }); Prio ...

Error message: "Unexpected token" encountered while using the three.js GLTFLoader() function

I have a requirement to load a .glb model into three.js by using the GLTFLoader. I was able to successfully create a rotating 3D mesh on a canvas without encountering any errors in the console. However, when I tried to replace it with the .glb model, I enc ...

Adjust the value based on selection

I aim to display another div when either the Full Time or Part Time option is selected. Additionally, I would like to calculate a different value for each option; if 'Part Time' is chosen, PrcA should change to PrcB. Here is the code snippet tha ...

Obtaining a byte array using the file input method

var profileImage = fileInputInByteArray; $.ajax({ url: 'abc.com/', type: 'POST', dataType: 'json', data: { // Other data ProfileImage: profileimage // Other data }, success: { } }) // Code in Web ...

Analyze and tally occurrences in two arrays

I have two arrays $array1=('18753933','18753933','18771982') $array2=('18753933','18771982') My goal is to compare the values that are the same in both arrays. var countArticlesLoaded=0; for(var $i=0;$i ...

Increase the size of the embedded iframe in your Cordova application by using the pinch-to-zoom

I have been struggling with this issue for the past few days and am having trouble finding a solution.. I am trying to figure out how to embed an iframe in a cordova app (running on an iOS device) to display an external webpage while allowing users to pin ...