Andrew O'Neill
Andrew O'Neill

Reputation: 255

Populating a HTML dropdown menu through a JavaScript function

Im trying to populate a dropmenu as described in the heading. At the moment I've this code:

<form id="myForm">
<select id="selectNumber">
     <option>Choose a number</option>
     <script>
         var myArray = new Array("1", "2", "3", "4", "5");
         for(i=0; i<myArray.length; i++) {  
             document.write('<option value="' + myArray[i] +'">' + myArray[i] + '</option>');
         }
     </script>
</select>
</form>

This works fine, but I have a large amount of variables in my array, so i want to put the script in a javascript file as a function and then call it in the html for aesthetic purposes.

So this is what i tried in the javascript file

function populate(){
    var myArray = new Array("1", "2", "3", "4", "5");
    for(i=0; i<myArray.length; i++) {  
        document.write('<option value="' + myArray[i] +'">' + myArray[i] + '</option>');
    }
}

And then I tried to call that method in the HTML like so :

<form id="myForm">
    <select id="selectNumber" onclick="populate()">
        <option>Choose a number</option>
    </select>
</form>

and this didn't work it just brought a new page and the numbers , but not in a dropdown menu to select from.

Any ideas on how to fix it would be much appreciated

Upvotes: 2

Views: 4517

Answers (2)

Josh Crozier
Josh Crozier

Reputation: 240858

As said in the comments, you should avoid document.write() and use a combination of createElement/appendChild instead.

You could also avoid inline JS and use unobtrusive JS instead:

var selectElement = document.getElementById('selectNumber'),
    optionArray = [1, 2, 3, 4, 5];

function populateSelectElement (element, array) {
    var newElement,
        i;
    for(i = 0; i < array.length; i += 1) {
        newElement = document.createElement('option');
        newElement.textContent = optionArray[i];
        element.appendChild(newElement);
    }
}
populateSelectElement(selectElement, optionArray);
<form id="myForm">
    <select id="selectNumber">
        <option>Choose a number</option>
    </select>
</form>

Then just attach a click event handler like this:

selectElement.addEventListener('click', function() {
    populateSelectElement(this, optionArray);
});

Upvotes: 1

Fuzzyma
Fuzzyma

Reputation: 8474

When using document.write() the script has to be executed while loading the page. You call the function with onclick which is obviously not while loading. Instead call the function directly:

<select id="selectNumber">
  <option>Choose a number</option>
  <script>
     populate();
  </script>
</select>

The javascriptfile has to be included before the function call

Upvotes: 0

Related Questions