1

I got 2 dropdown menus in my website, one applies when user is in the phone, other is when user is on desktop.I use this code:

function populateSelect(target, min, max){
if (!target){
    return false;
}
else {
    var min = min || 0,
        max = max || min + 100;

    select = document.getElementById(target);

    for (var i = min; i<=max; i++){
        var opt = document.createElement('option');
        opt.value = i;
        opt.innerHTML = i;
        select.appendChild(opt);
    }
  }
}

populateSelect('howMany6');

Both dropdowns share same id:

<select class="form-control" id="howMany6" name="mituKeyd6" onChange="paljuKokku()"></select>

But javascript only adds options to the mobile version of dropdwon, beacuse mobile code is before desktop code in HTML. How can i make javascript code to add options for both of the dropdown menus?

Carel155
  • 31
  • 1
  • 2
  • 6

1 Answers1

0

Don't duplicated ids, keep them unique. Instead use classes to refer groups of elements.

In your case you will need to loop over collection of elements and populate each of them separately.

function populateSelect(target, min, max) {
    if (!target) {
        return false;
    } 
    else {
        var min = min || 0,
            max = max || min + 100,
            select = document.querySelectorAll(target);

        for (var j = 0; j < select.length; j++) {
            for (var i = min; i <= max; i++) {
                var opt = document.createElement('option');
                opt.value = i;
                opt.innerHTML = i;
                select[j].appendChild(opt);
            }
        } 
    }
}

populateSelect('.howMany6');
<select class="form-control howMany6" name="mituKeyd6" onChange="paljuKokku()"></select>
<select class="form-control howMany6" name="mituKeyd6" onChange="paljuKokku()"></select>
dfsq
  • 191,768
  • 25
  • 236
  • 258