I'd suggest performing math on the variable that refers to the year, as you increment (or decrement) through the for loop, simply add, or remove, the incrementing variable (i in this case) to, or from, the variable holding the year:
function addYears(el, num) {
if (!el) {
return false;
}
else {
for (var i=0; i < num; i++) {
var opt = document.createElement('option'),
year = new Date().getFullYear() - i;
opt.value = year;
opt.textContent = year;
el.appendChild(opt);
}
}
}
addYears(document.getElementById('years'), 18);
JS Fiddle proof of concept.
In your code excerpt, I'd suggest amending things to:
function allYears(){
var d = new Date();
var y = d.getFullYear();
var years = '';
for(var i=0; i<18; i++){
years += '<option value="'+ (y - i) +'">'+ (y - i) +'</option>';
}
return(years);
}
Which, as the loop progresses, should return option elements with year values progressively earlier than the year held in y.
Also, the middle condition in the for loop is the evaluation that has to be true for the loop to continue (when it stops being true is when the loop exits), so it should be i < 18 (since i starts equal to 0).
d.getFullYearshould bed.getFullYear()i = 0and0 > 18isfalse.