[英]Dynamically add options to select select tag
I am trying to write a select drop down which is dynamically filled up with options, the options are the years, eg 2010, 2011, 2012 我正在尝试编写一个选择下拉列表,其中动态填充了选项,这些选项是年份,例如2010、2011、2012
But with each coming year the webpage should add new entry in the drop down with the current year. 但是,随着明年的到来,该网页应该在与当年的下拉列表中添加新条目。 The first entry of the year is 2010 fixed but the last entry is dynamic and depends on the current year..
该年度的第一项是固定的2010年,但是最后一项是动态的,并且取决于当年。
Any help? 有什么帮助吗?
Something like this? 像这样吗
var currentYear = new Date().getFullYear(); for (var i = 2010; i <= currentYear; i++) { var selected = ''; if (i == currentYear) selected = 'selected'; $("#years").append("<option value='" + i + "'" + selected + ">" + i + "</option>") }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id='years' />
Why don't you select the current year substract 2010 from it ( because it is a fix end) and then you will count up from 2010 adding the amount from your result? 为什么不从中选择当前年份减去2010(因为这是一个固定的结束时间),然后从2010开始加总结果中的金额呢? Thats how I would do that with the first thoughts.
那就是我将如何用最初的想法做到这一点。
Edit: If you fill the dropdown on each load of the page you always fill that array with the amount calculated from your substraction. 编辑:如果您在页面的每次加载中填充下拉列表,则始终使用从您的减法计算出的数量填充该数组。 I don't get the problem.
我没问题。
Here is the jsfiddle link (without jquery). 这是jsfiddle链接(没有jquery)。
<form>
<select id="mySelect">
</select>
</form>
Javascript: Javascript:
var x = document.getElementById("mySelect");
var to = new Date().getFullYear();
var option;
for (var i = 2010; i <= to; i++)
{
option = document.createElement("option");
option.text = i;
x.add(option);
}
Just use the actual date : 只需使用实际日期:
var startYear = 1950;
var currentYear = new Date().getFullYear();
And then you can generate your select options 然后您可以生成选择选项
var select = '<select>';
for (var i = startYear; i <= currentYear; i++){
select += '<option>'+i+'</option>';
}
select += </select>;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.