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
2 Answers
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
版权声明:本文标题:javascript - Loop through years in a dropdown - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742032510a2416715.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论