HTML looping option values in drop down list

六月ゝ 毕业季﹏ 提交于 2019-12-05 07:27:14

问题


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>


来源:https://stackoverflow.com/questions/20873302/html-looping-option-values-in-drop-down-list

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