I have been trying to do a form where a question about one's current age is included, and I have decided the easiest way to answer this question is by filling in a drop down list. So my first value in the drop down list shall be 1900 and then it shall increment by one till it reaches 2014. How do I do that?
I wouldn't set a fixed final year, why recode again next year?
Note that it is more effecient to update the DOM once than updaing the DOM for each year added to the list.
HTML
<select id="year"></select>
Script
var start = 1900;
var end = new Date().getFullYear();
var options = "";
for(var year = start ; year <=end; year++){
options += "<option>"+ year +"</option>";
}
document.getElementById("year").innerHTML = options;
<select id="year"></select>
var year = 1900;
var till = 2014;
var options = "";
for(var y=year; y<=till; y++){
options += "<option>"+ y +"</option>";
}
document.getElementById("year").innerHTML = options;
Duke
a php version?
Birth Year:
<input list="birth_year" name="year_born">
<datalist id="birth_year">
<?php
$right_now = getdate();
$this_year = $right_now['year'];
$start_year = 1900;
while ($start_year <= $this_year) {
echo "<option>{$start_year}</option>";
$start_year++;
}
?>
</datalist>
</input>
<!DOCTYPE html>
<html>
<body onload="loadAgeSelector()">
<select id="yearselect"></select>
<script>
function loadAgeSelector()
{
var startyear = 1900;
var endyear = 2014;
for (var i = startyear;i<=endyear;i++){
node=document.createElement("Option");
textnode=document.createTextNode(i);
node.appendChild(textnode);
document.getElementById("yearselect").appendChild(node);
}
}
</script>
</body>
</html>
来源:https://stackoverflow.com/questions/20873302/html-looping-option-values-in-drop-down-list