HTML looping option values in drop down list

2019-04-03 01:52发布

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?

4条回答
乱世女痞
2楼-- · 2019-04-03 02:22

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

查看更多
孤傲高冷的网名
3楼-- · 2019-04-03 02:31

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;
查看更多
做个烂人
4楼-- · 2019-04-03 02:32

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>
查看更多
欢心
5楼-- · 2019-04-03 02:44
<!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>
查看更多
登录 后发表回答