Iterating over chosen tags to generate an array or string

I need help creating a loop that will generate the following output:

"1 dropdown1, 1 dropdown2, 2 dropdown3, 2 dropdown4, 3 dropdown5, 3 dropdown5...... "

either as a string or an array.

This is the code I have written so far, but I have hit a roadblock:

var selects = document.getElementById("getAllRecordsDiv").getElementsByTagName("select");
for(var l = 0; l < selects.length; l++) {
    for (var i = 0; i < 2; i++) {
        var options = i + " " + selects[l].options[selects[l].selectedIndex].text;
    }            
}

    <div id="getAllRecordsDiv" style="border: 2px solid gray; padding: 5px; display: none">        
       <select name="" id="dd1" style="" onchange="">
          <option value="0">one</option>
          <option value="0">two</option>            
       </select>
       <select name="" id="dd2" style="" onchange="">
          <option value="0">three</option>
          <option value="0">four</option>
       </select>
       <select name="" id="dd3" style="" onchange="">
          <option value="0">five</option>
          <option value="0">six</option>            
       </select>
       <select name="" id="dd5" style="" onchange="">
         <option value="0">seven</option>
         <option value="0">eight</option>           
       </select>
    </div>

Any assistance would be greatly appreciated.

Answer №1

Now that you've provided your final explanation, I understand your needs. Here is the revised code:

var selects = document.getElementById("getAllRecordsDiv").getElementsByTagName("select");
var mainCount = countTo2 = 1;
var strOptions = '';
for (var l = 0; l < selects.length; l++) {
    var options = selects[l].getElementsByTagName("option");
    for (var i = 0; i < options.length; i++) {
         var option = mainCount + " " +  options[i].text + ", ";                    
         strOptions += option;
         countTo2++;
         if (countTo2 > 2) {
            countTo2 = 1;
            mainCount++;
         }
    }            
}

alert(strOptions);

Feel free to check out the final example here:

https://jsfiddle.net/53j3cgo2/6/

I've also included a more advanced example for further study:

function nodeListToArray(nodeList) {
    return Array.prototype.slice.call(nodeList);
}

var selects = nodeListToArray(document.getElementById("getAllRecordsDiv").getElementsByTagName("select"));
var cnt = 1;
var options = '';
selects.forEach(function(select) {
    nodeListToArray(select.getElementsByTagName("option"))
        .forEach(function(option) {
            options += ((cnt+(cnt % 2))/2)  + " " +  option.text + ", ";                    
            cnt++;
        });
});

alert(options);

You can find the advanced example here:

https://jsfiddle.net/53j3cgo2/10/

There are always better ways to achieve this. I recommend diving deeper into JS objects, AMD, and IIFEs for a more comprehensive understanding. Keep exploring! :)

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

The code is throwing a SyntaxError because it encountered an unexpected character in the JSON file at position 650xx

I am encountering an issue when attempting to save a JSON-formatted file from within the Javascript app I am developing. The app is running on Node v6.11.0 with Express on my local machine, port 3000. Occasionally, I come across the following error: Synta ...

Handling errors within classes in JavaScript/TypeScript

Imagine having an interface structured as follows: class Something { constructor(things) { if (things) { doSomething(); } else return { errorCode: 1 } } } Does this code appear to be correct? When using TypeScript, I en ...

How to effectively pass custom props or data to the Link component in Next JS

As I dive into Next JS, I've hit my first roadblock. Currently, I am working on a page that showcases various podcast episodes with preview cards on the homepage. The card component code looks like this: import React from 'react'; import Li ...

Scene three js appears to be stuck in a perpetual state of emptiness, making it challenging to start

I've encountered a major issue with understanding how to use three.js. Despite my best efforts over the past few days, I haven't been able to successfully implement three.js into my projects. Initially, I attempted using Parcel by starting a new ...

Mongoose: when the item exists, increase the count; otherwise, add it to the array

Hey there, I've got a model setup like this: articles: [ { _id: { type: ObjectId, ref: "Article" }, amount: { type: Number } } ] The goal is to check if an article already exists in the array ...

Is it possible to extract an attribute value from a parent element using ReactJS?

https://i.stack.imgur.com/OXBB7.png Whenever I select a particular button, my goal is to capture the {country} prop that is linked to it. I attempted the following approach import React, { useState, useEffect } from 'react' import axios from &ap ...

Guide to capturing and playing audio on iOS6 with HTML5

Our team is currently working on a web application using HTML5 and Javascript. We are facing a challenge with implementing voice recording functionality, as the Wami Api we tried is not compatible with iPad due to its use of flash for recording. Could yo ...

Transferring information to a controller using ajax in ASP.NET Core

I am encountering an issue with sending data to the controller through ajax. The value goes as "null". Can someone please assist me with this? Here are my HTML codes: <div class="modal fade" id="sagTikMenuKategoriGuncelleModal" data ...

Interactive YouTube Video Player that keeps video playing in original spot upon clicking the button

Currently, I'm working on a project that involves combining navigation and a video player within the same div container. Here is an image link And another image link The concept is that when you click on one of the four boxes, a new video will appe ...

Tips for resolving issues with dynamically displaying state information based on a selected country

I'm currently working on a project that requires me to dynamically fetch the states of a specific country when a user selects the country of birth for their family members. To do this, I am utilizing AJAX. Due to limitations, I can only include detai ...

Using HTML5 video with cue points and stop points

I've noticed that there are various options available for implementing cuepoints in HTML5 videos, such as using PopcornJS or CuepointsJS to trigger play events at specific times within the video track. However, I am wondering if there is a solution t ...

vue.js: Modifying information through watcher function

Here is the code I am currently using: export default { name: '...', props: ['user'], data() { return { userName: this.user.name } }, watch: { user: (_user) => { th ...

Explore various locations and conceal different divs by clicking

Can someone help me figure out how to hide the placeholders when the focus changes in a form? Here is the code snippet that illustrates my problem. Your assistance is greatly appreciated, João var inputs = Array.prototype.slice.call(document.querySele ...

Retrieve data from the following fields: {"attending":0,"eventid":1,"userid":1} using PHP

After receiving an array from JAVA and using print_r($_POST), I have tried various methods to extract data but with no success. The format of the array is as follows: {"attending":0,"eventid":1,"userid":1} I've attempted different approaches found o ...

Is there a way to extract information from the HTML source code of an external website and display it in my application?

Seeking a method to search an external URL for content that matches "title" and then display the results on my HTML page using Javascript. Despite my efforts with Javascript, I have not come across any resources that address this issue. Could it be that I ...

Display the json encoded result of a MySQL SUM() query

I am attempting to use JSON to print the total sum of a price. Here is my current approach: $query="SELECT SUM(cost) FROM `Service`"; $result = mysql_query($query); $json = array(); while($row = mysql_fetch_array($result)) { $json[&a ...

Fill a specific portion of a Java array with predetermined values

Consider the following array: int[] array = new int[size]; I am looking to populate 30% of the array with the number 2 and the remaining 70% with the number 8, depending on its size. How can this be accomplished? Additionally, there may be more than two ...

Using an array as an argument for .map() results in an error

This is quite unusual. Currently, I am passing an array containing a single object to the Render method of a React component: let content = this.state.links.map(link => { // eslint-disable-line return ( <li key={link._id}> <a href ...

You are unable to insert a variable within the channels.get() method in discord.js

Attempting to troubleshoot this issue has been quite frustrating. Despite my efforts, it seems that something is not working as expected. I can't help but wonder if I am simply overlooking a simple mistake due to fatigue. Here's the scenario: It ...

What could be the reason for my mongoose model failing to save in mongodb?

I am experiencing an issue with my simple Post model and route for creating posts. After submitting a new post using Postman, the request hangs for a moment before returning an error in JSON format. The model data is never saved successfully. Below is the ...