HTML looping option values in drop down list

霸气de小男生 提交于 2019-12-03 22:42:00

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

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;
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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!