'Jquery - Automatically add current year months to dropdown
I am trying to automatically add the current months of the year, for the current year to a Bootstrap dropdown list.
Currently, I am adding them manually as I am not very good at JavaScript.
How can I automatically add the current months left in the year to the list?
Now we are in February it wouldn't add January cause its already passed.
I have made a bootply so you can see what I mean.
Solution 1:[1]
To achieve this you can get the month from the current date using getMonth()
. From there you can loop through the remaining months and populate a select
, something like this:
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var month = (new Date()).getMonth();
for (; month < monthNames.length; month++) {
$('select').append('<option>' + monthNames[month] + '</option>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select></select>
This basic logic can in turn be reduced to this:
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var html = monthNames.slice((new Date()).getMonth()).map(function(month) {
return '<option>' + month + '</option>';
}).join('');
$('select').html(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select></select>
Solution 2:[2]
Below is my example which helped to me display ONLY VALID Months for the current year or All Months for Previous Years in a Cascading Dropdown of Month.
This Example below will disable Cascaded Month Drop if Invalid Year is Selected and will also take care of current valid months as per the choice of the year.
var currentYear = new Date().getFullYear();
var currentMonth = new Date().getMonth();
var cascadedDropDownMonthId = "#dropDownYearMonth";
//Adding Last 10 Years to Year Drop Down
for (var i = currentYear;i > currentYear - 10 ; i--)
{
$("#dropDownYear1").append('<option value="'+ i.toString() +'">' +i.toString() +'</option>');
}
//Disabling Month Dropdown in case of invalid Selections.
$(cascadedDropDownMonthId).prop("disabled", true);
$("#dropDownYear1").change(function () {
var currentSelectedValue = $(this).val();
if (currentSelectedValue == "-1")
{
$(cascadedDropDownMonthId).prop("disabled", true);
}
else
{
$(cascadedDropDownMonthId).prop("disabled", false);
//Get Current Year from Dropdown and Converting to Integer for performing math operations
var currentSelectedYear = parseInt($(this).val());
//As Index of Javascript Month is from 0 to 11 therefore totalMonths are 11 NOT 12
var totalMonths = 11;
if (currentSelectedYear == currentYear) {
totalMonths = currentMonth;
}
var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
//Emptying the Month Dropdown to clear our last values
$(cascadedDropDownMonthId).empty();
$(cascadedDropDownMonthId).append('<option value="-1">-Month-</option>');
//Appending Current Valid Months
for (var month = 0; month <= totalMonths; month++) {
$(cascadedDropDownMonthId).append('<option value="'+ (month+1) + '">' + monthNames[month] + '</option>');
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="dropDownYear1">
<option value="-1">-Year-</option>
</select>
<select id="dropDownYearMonth">
<option value="-1">-Month-</option>
</select>
Solution 3:[3]
As an alternative, where the Intl object is supported, month names are available from Date.prototype.toLocaleString. This can adopt the browser default language or you can set it.
See MDN Date.prototype.toLocaleString() and the support matrix. I doesn't work in IE 10 or lower, but there's good support in other browsers.
E.g.
function addRemainingMonthOptions(id, lang) {
// Make sure element exists
var sel = document.getElementById(id);
if (!sel) return;
// Get current date, set day to 1 so not affected by adding months
var d = new Date();
d.setDate(1);
// Add options until end of year
do {
month = d.toLocaleString(lang,{localeMatcher: 'best fit', month:'short'})
sel.appendChild(new Option(month, month));
d.setMonth(d.getMonth() +1);
} while (d.getMonth() > 0)
}
// Add remaining months in browser default langauge (lang is undefined)
addRemainingMonthOptions('theMonth0')
// … in Russian
addRemainingMonthOptions('theMonth1', 'ru')
// … in Arabic
addRemainingMonthOptions('theMonth2', 'ar')
<select id="theMonth0">
</select>
<select id="theMonth1">
</select>
<select id="theMonth2">
</select>
Solution 4:[4]
$('#fyyear').click(function(){
var currentYear = new Date().getFullYear();
var nextYear = new Date().getFullYear()+1;
var currentMonth = new Date().getMonth()-3;
var monthList = "#month";
var fy = currentYear +'-'+nextYear;
var currentFYear = $('#fyyear').val();
var totalMonths = 11;
if(currentFYear == fy)
{
totalMonths = currentMonth;
}
var monthNames = ["April","May", "June", "July", "August", "September", "October", "November", "December","January", "February", "March"];
$(monthList).empty();
for (var month = 0; month <= totalMonths; month++)
{
$(monthList).append('<option>' + monthNames[month] + '</option>');
}
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | |
Solution 3 | RobG |
Solution 4 | Swapnil Potdar |