admin管理员组

文章数量:1317906

I would like to display the current year and 10 years before that year.

Is it any way to do that through JavaScript or jQuery?

Currently, I am manually inputting values.

HTML:

<span>Year:</span>
<select name="year">
    <option value="2014">2014</option>
    <option value="2013">2013</option>
    And so on....
</select>

I know how to get the current year in JavaScript

Here's what I have currently

var d = new Date();
var y = d.getFullYear();

I would like to display the current year and 10 years before that year.

Is it any way to do that through JavaScript or jQuery?

Currently, I am manually inputting values.

HTML:

<span>Year:</span>
<select name="year">
    <option value="2014">2014</option>
    <option value="2013">2013</option>
    And so on....
</select>

I know how to get the current year in JavaScript

Here's what I have currently

var d = new Date();
var y = d.getFullYear();
Share Improve this question asked Oct 13, 2014 at 15:14 user4100421user4100421 1371 gold badge3 silver badges9 bronze badges 2
  • Can you post a sample of what you've attempted to do in JavaScript? – chsh Commented Oct 13, 2014 at 15:15
  • 1 Yes. You can do that. Did you try anything? – karthick Commented Oct 13, 2014 at 15:15
Add a ment  | 

2 Answers 2

Reset to default 7

$(function() {
  var start_year = new Date().getFullYear();

  for (var i = start_year; i > start_year - 10; i--) {
    $('select').append('<option value="' + i + '">' + i + '</option>');
  }
});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span>Year:</span>
<select name="year"></select>

But a templating engine like mustache.js would be better suited for that job, so you can avoid having markup code in your javascript.

html

<select name="example" id="select" ></select> 

Javascript version

(function(){
    var start_year = new Date().getFullYear();
    var html ='';
    for (var i = start_year; i > start_year - 10; i--) {
       html += '<option value="'+i+'">'+i+'</option>';
    }
   document.getElementById("select").innerHTML = html;
})()

Jquery version

$(function() {
  var start_year = new Date().getFullYear();
  var html = ''
  for (var i = start_year; i > start_year - 10; i--) {
    html += '<option value="'+i+'">'+i+'</option>';
  }
 $("#select").html(html)
});

本文标签: javascriptLoop through years in a dropdownStack Overflow