Populate a dropdown menu using Javascript

[Code]

$.ajax
({
    'method': 'GET',
    'source': '/bpv-registratie/periods/show_period_list_by_year.html',
    'charge': function () 
    {
    },
    'finish': function (xmlHttp) 
    {       
        var options = new Array();
        var response = eval('(' + xmlHttp.responseText + ')');                                              

        var child = document.createElement('option');
        child.setAttribute('value', 'none');
        child.setAttribute('checked', 'checked');
        child.innerHTML = '&nbsp';

        options.push(child);

        for (var c = 0; c < response.length; c++)
        {
            var child = document.createElement('option');
            child.setAttribute('value', response.data[c].periode_id);
            child.innerHTML = response.data[c].periode_naam +
                              ' (' + 
                              response.data[c].periode_startdatum +
                              ' t/m ' +
                              response.data[c].periode_einddatum +
                              ' )';             
            options.push(child);
        }                                               
        for (var a = 0; a < obj.childNodes.length; a++)
        {
            var e = obj.childNodes[a].getElementsByTagName("select");

            for (var f = 0; f < e.length; f++)
            {       
                e[f].length=0;                  
                for (var o = 0; o < options.length; o++)
                {               
                    e[f].appendChild(options[o]);               
                }
            }
        alert('test');
        }   
    }
});

[Problem]

Upon running the aforementioned code with the alert, it indicates that all select boxes are getting filled with the desired options. However, when it proceeds to fill the next select box, the previous one gets cleared again. Any insights on why this is happening?

[Situation]

A series of select boxes have been generated using similar code. These represent classes that an individual can be enrolled in. The user must select a class from these select boxes. Nevertheless, if an instructor wishes to switch the person to a different period, which likely entails having different classes available during that time, my goal is to populate the select boxes with classes from the new period.

Answer №1

It appears that the issue lies in the fact that a single option object can only belong to one <select> at a time. Your code seems to first populate one select element within a loop and then transfer the options to another select element in subsequent iterations of the loop. This process repeats until all options end up in the final select element.

A better approach would be to create the options dynamically before adding them to the <select>. Instead of directly populating each select element, you can first build an array containing data for values and labels. Then, convert this data into option elements and assign them to the corresponding <select>, ensuring that each select element has unique option objects.

For a clearer understanding, you can experiment with the provided example:

http://jsfiddle.net/ambiguous/9WuQC/

To facilitate future reference, here is the HTML snippet included:

<select id="a"></select>
<select id="b"></select>
<button id="c">fill first</button>
<button id="d">fill second</button>

Accompanied by the JavaScript code:

var options = [ ];
var option;
for(var i = 0; i < 10; ++i) {
    option = document.createElement('option');
    option.setAttribute('value', i);
    option.innerHTML = i;
    options.push(option);
}

$('#c').click(function() {
    var s = document.getElementById('a');
    for(var i = 0; i < options.length; ++i)
        s.appendChild(options[i]);
});
$('#d').click(function() {
    var s = document.getElementById('b');
    for(var i = 0; i < options.length; ++i)
        s.appendChild(options[i]);
});

Answer №2

While I'm uncertain about the true nature of obj, let me share my interpretation with you:

//loop through all child nodes of obj (not limited to immediate children)
for (var a = 0; a < obj.childNodes.length; a++)
{
    //retrieve all <select> elements under the current child (a) of obj 
    var e = obj.childNodes[a].getElementsByTagName("select");

    //iterate through our selects under the current child node
    for (var f = 0; f < e.length; f++)
    {       
        e[f].length=0;                  
        for (var o = 0; o < options.length; o++)
        {               
            e[f].appendChild(options[o]);               
        }
    }
    alert('test');
}   

The comment 'not just immediate' holds significance here. Consider a structure like this

<div id="a">
    <div id="b">
        <div id="c">
             <select id="d"></select>
        </div>
    </div>
</div>

When iterating through the children of 'a', you encounter ALL children, namely b,c,d. On subsequent iterations within the child loop, you're examining 'b' itself, which includes 'c' and 'd'.

Essentially, you are filling the select box in each of these loops.

In essence, it's likely that there might be a misconception regarding the childNodes property.

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

What causes the component to remount with every update to its state?

PLEASE NOTE: Before posting this question, I realized that there were some errors in my code. I understand now that this question may not be helpful to others as it contains misleading information. I apologize and appreciate those who took the time to res ...

The CSS and JS codes are not successfully integrating into the webpage

I am encountering an issue with loading CSS and JS files onto my page. My project involves PHP and Xampp. The file structure is as follows: My Site - CSS - index.css - JS - index.js - Index.php (Apologies for the lack of a folder tre ...

Utilizing Angular to augment existing items in local storage

Hey everyone, I'm facing an issue with localStorage that I can't seem to figure out. I have a form where the first step collects name and gender, and the second step asks for weight and height. The data from step 1 is saved in localStorage, but ...

Send a res.json response and retrieve it using res.render in a different router

Trying to retrieve a JSON from the route "/api/product" and display it using hbs on the "/product" route. The code seems to be working, but is it done correctly? The router in this case is: '/api/product' router.get('/', this.controll ...

Mask the "null" data in JSON

I'm currently working with a JSON file and trying to display it in a bootstrap table. Check out the code snippet I've been using: $(document).ready(function(){ $.getJSON(url, function(data){ content = '<h1><p class="p1 ...

How can I create a regex pattern that will exclude characters within parentheses?

While working on some regex, I encountered a bug: The scenario is as follows: I have this string - for example "+1/(1/10)+(1/30)+1/50" and I applied the regex /\+.[^\+]*/g to it, which worked perfectly giving me ['+1/(1/10)&apos ...

Receive the output from a function and pass it as an input to another function in PHP

Here is the code for file upload functionality: The goal is to have a function return the file path so it can be used in another function, specifically in the send_email function: public function add_attachments($ticket_id) { $config['up ...

Guide to refining a JSON array using a pre-established list

I'm in need of assistance figuring out how to accomplish the following task: Below is the code snippet I am working with: public class Data { public string FirstName; public string LastName; public int Age; } var data = new Data { //this objec ...

Express server failing to serve js and css files

Currently, I'm working on a ReactJS project with React Router implemented. When attempting to access /dashboard/stream, the server is returning the index.html file successfully. However, there are 301 errors for the CSS and JS files, resulting in noth ...

Begin the Wordpress AJAX Login

Is there a way to trigger the code below when a user is logged out from another location due to user inactivity, similar to how wp-admin displays an AJAX login overlay if a user is logged out? I have not come across any documentation or tutorials on achiev ...

The CSS and Bundle script path may need adjustment following the creation of the index.html file by WebPack

There seems to be an issue with webpack trying to add 'client' to the href of script tags for my CSS and bundle files. This is causing a problem as it's incorrect and I'm unsure how to remove it. Prior to switching to webpack, here&apo ...

What is the best way to send a prop to my home route following a redirect?

I am working with react-router-dom and I want to pass :id to my first route (/) when redirecting. This is important so that I can access :id in my Interface component and maintain consistent URL structure for my single-page application. Is it feasible to a ...

Display the device model using Google Cloud Monitoring API

I've been utilizing a Node.js library to fetch metrics from my Google Cloud Compute Engine instances. You can find the library here. When creating a time series, the resulting data looks like this: { "points": [...], "metric": { "lab ...

Tips for ensuring that a THREE.Group is always displayed in front of other objects

I am attempting to display a set of transform controls in such a way that they are constantly visible to the user. However, when I disable DepthWrite or apply the AlwaysDepth function to the transform controls, I achieve the desired result but encounter an ...

Configuring Vue.js watchers inside a for loop

Exploring the dynamic addition of watchers in Vue.js. The discrepancy between what is desired and what actually happens is demonstrated below in the commented section. As a casual coder, I believe my issue lies more in grasping JavaScript basics rather t ...

ng-model in html input with a name of "foo[]"

Apologies for the lack of a more specific title. In HTML, when we need multiple values for a given name, we utilize the name="foo[]" attribute. Upon posting the data, it arrives as an array. I am seeking this same functionality with ng-model in Angular. ...

Switch up the current Slick Carousel display by utilizing a div element

We have implemented the slick carousel to show only one slide at a time within the <div class='item__wrapper'>. Beneath this are three items, and we want the slick carousel to update when any of these items are clicked. Issues Using item ...

Using a click event to target the next div and apply a CSS class using Typescript

I am trying to create a Typescript function that will locate the next div and apply a CSS class to it. Here is what I have attempted: <ul> <li><a href="#" onclick="toggle()">Item 1</a></li> <div class="content hide ...

Angular - Ensure completion of a function call before continuing with the code execution

I'm currently working on developing a code snippet that checks for potential adverse drug reactions between two medications. Within my checkForClash() function, there is a call to getCollisionsList(), which is responsible for populating the interacti ...

How can I convert a list of checkboxes, generated by ng-repeat, into multiple columns?

Here is the HTML code snippet: <div class="checkbox"> <label> <input type="checkbox" ng-model="selectedAll.value" ng-click="checkAll()" />Check All </label> </div> <div class="checkbox" ng-repeat="carType i ...