Reputation: 37
I'm trying to populate select options with results from a for cycle but I just can't get it to work. I call the function from the select's onclick but it just doesn't work.
Here's a working JS fiddle without the function but I need it to be in a function.
http://jsfiddle.net/t8fdh/610/
And here's what I'm trying to get to work.
http://jsfiddle.net/t8fdh/612/
function populate() {
var max = new Date().getFullYear() + 1,
min = max - 9,
select = document.getElementById('selectElementId');
for (var i = min; i <= max; i++) {
var opt = document.createElement('option');
opt.value = i;
opt.innerHTML = i;
select.appendChild(opt);
}
};
<select id="selectElementId" onload="populate()"></select>
Upvotes: 1
Views: 96
Reputation: 2725
Why using onload
on the select
element, try adding the execution of populate()
function on the window load
using window.onload = populate();
window.onload = populate();
function populate() {
var max = new Date().getFullYear() +1;
var min = max - 9;
select = document.getElementById('selectElementId');
for (var i = min; i<=max; i++){
var opt = document.createElement('option');
opt.value = i;
opt.innerHTML = i;
select.appendChild(opt);
}
};
<select id="selectElementId" ></select>
Upvotes: 2
Reputation: 387
According to https://www.w3schools.com/tags/ev_onload.asp, you can only use onload on the following tags:
<body>, <frame>, <frameset>, <iframe>, <img>, <input type="image">, <link>, <script> and <style>
You can put your onload on the body tag and it will work :)
Upvotes: 0
Reputation: 1456
It works if you use document.onload();
jsfiddle: http://jsfiddle.net/t8fdh/616/
Upvotes: 1