Skip to content Skip to sidebar Skip to footer

Updating Multiple Select Boxes Dynamically

I have a page that has 2-300 select dropdown boxes. I need to dynamically update each one to have the same list of options. Each time I try to update it it only does the first one.

Solution 1:

Just as Mike said, you can't use the same ID field for all your selects.

"An ID should be unique within a page. However, if more than one element with the specified ID exists, the getElementById() method returns the first element in the source code."

You could try setting the same class to your selects and then use getElementsByClassName(class), which returns all the elements with that class.

Also, if there is no other select element in your page aside from the ones you want to change you could use getElementsByTagName('select') which returns all the select elements.

Solution 2:

You can use getElementById for your form id and save it to some variable

as in below code then use that variable with getElementsByTagName

to get all your dropdown of your form.

I modified your html, see below and use this script

window.onload = function() {
          var myFormdropdown = document.getElementById("myForm");
          var varselect = myFormdropdown.getElementsByTagName("select");
          var myArray = newArray("1", "2", "3", "4", "5");
          
          // Loop through the arrayfor (var j = 0; j < varselect.length; j++) {
            for (var i = 0; i < myArray.length; ++i) {
              // Append the element to the end of Array list                    var option = document.createElement('option');
              option.value = myArray[i];
              option.innerHTML = myArray[i];
              varselect[j].options.add(option);
            }
          }
        };
<formid="myForm"><selectid="selectNumber"><option>Choose a number</option></select><selectid="selectNumber"><option>Choose a number</option></select><selectid="selectNumber"><option>Choose a number</option></select></form>

Hope this will help you.

Post a Comment for "Updating Multiple Select Boxes Dynamically"