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?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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;
Example
回答2:
DEMO
<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;
回答3:
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>
回答4:
<!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>