我尝试自动创建具有以下内容的选择列表:
<select name="Range" id="ranges">
<option value="July 2017">July 2017</option>
<option value="June 2017">June 2017</option>
<option value="May 2017">May 2017</option>
一直到2015年8月
<option value="August 2015">August 2015</option>
</select>
第一个选项必须是当前的月份和年份
这可以通过javascript自动填充吗?
答案 0 :(得分:1)
这是一个针对您的需求的更新解决方案,只有简单的JQuery而没有datepicker:
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var currentMonthName = months[new Date().getMonth() + 1];
for (i = new Date().getFullYear(); i > 2014; i--) {
$.each(months, function(index, value) {
if (i == 2015 && value == 'Sep')
return false;
if (i == new Date().getFullYear()) {
if (value == currentMonthName) {
return false;
} else {
$('#yearMonthInput').append($('<option />').val(index + "_" + i).html(value + " " + i));
}
} else {
$('#yearMonthInput').append($('<option />').val(index + "_" + i).html(value + " " + i));
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control" id="yearMonthInput"></select>
答案 1 :(得分:1)
你可以在现在和Aug 1, 2015
之间获得几个月的数组,然后使用该数组在select中做出选项,如下所示:
function dateRange(startDate, endDate) {
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
var startMonth = parseInt(startDate.getMonth());
var endMonth = parseInt(endDate.getMonth());
var startYear = parseInt(startDate.getFullYear());
var endYear = parseInt(endDate.getFullYear());
var dates = [];
for (var i = startMonth; i >= 0; i--)
dates.push(monthNames[i] + " " + startYear);
startYear--;
for(var i = startYear; i > endYear; i--) {
for (var j = monthNames.length-1; j >= 0; j--)
dates.push(monthNames[j] + " " + i);
}
for (var i = monthNames.length-1; i >= endMonth; i--)
dates.push(monthNames[i] + " " + endYear);
return dates;
}
dates = dateRange(new Date(), new Date('August 1, 2015'));
var select = document.getElementById('datepicker');
dates.forEach(function(d){
select.options.add(new Option(d, d));
});
&#13;
<select id="datepicker"></select>
&#13;
答案 2 :(得分:0)
我的代码,也许它不是很小很漂亮,但是......)
let date = new Date();
let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
let currentYear = date.getFullYear();
let currentMonth = date.getMonth();
let lastYear = date.getFullYear() - 2;
let lastMonth = date.getMonth() + 1;
let objectOfDates = [];
for (let j = 0; j < months.length; j++) {
objectOfDates.unshift(`${months[j]} ${currentYear - 1}`);
};
for (let i = 0; i <= currentMonth; i++) {
objectOfDates.unshift(`${months[i]} ${currentYear}`);
};
for (let k = 11; k >= lastMonth; k--) {
objectOfDates.push(`${months[k]} ${currentYear - 2}`);
};
let select = document.querySelector('select[name="Range"]');
objectOfDates.forEach(function(value){
select.options.add(new Option(value, value));
});
<select name="Range" id="ranges">
</select>