Jith
Jith

Reputation: 109

appendChild to multiple dropdowns

so I wanted to populate 2 different dropdown with the same things. However with this code its only populating one of them, and I'm not sure why it wont add it to both

$.getJSON('http://' + document.domain + ':' + location.port + '/db/casters', function(data){
        console.log(data);
        var caster1 = document.getElementById('caster1');
        var caster2 = document.getElementById('caster2');
        for(var i=0; i<data.length; i++){
            var opt = data[i];
            var el = document.createElement("option");
            el.textContent = opt['caster_name'];
            el.value = opt['id'];
            caster1.appendChild(el);
            caster2.appendChild(el);
        }});

It only populates to the second one, and it doesn't make sense to run a second for loop to populate it. I'm not sure what I can do to fix it.

Upvotes: 1

Views: 340

Answers (1)

Lazar Petrovic
Lazar Petrovic

Reputation: 133

You are trying to append a singular element to multiple components/other elements. You could make another one and append that to the other list.

$.getJSON('http://' + document.domain + ':' + location.port + '/db/casters', function(data){
        console.log(data);
        var caster1 = document.getElementById('caster1');
        var caster2 = document.getElementById('caster2');
        for(var i=0; i<data.length; i++){
            var opt = data[i];
            var el = document.createElement("option");
            const el2 = document.createElement("option") // like here
            el.textContent = opt['caster_name'];
            el2.textContent = opt['caster_name']; // here
            el.value = opt['id'];
            caster1.appendChild(el);
            caster2.appendChild(el2); // and here as well
        }});

Upvotes: 2

Related Questions