Skip to content

Instantly share code, notes, and snippets.

@miteshmap
Created July 12, 2019 14:56
Show Gist options
  • Save miteshmap/83e326ace9d1ae3dabf6e671267315e7 to your computer and use it in GitHub Desktop.
Save miteshmap/83e326ace9d1ae3dabf6e671267315e7 to your computer and use it in GitHub Desktop.
You don't need jquery
// With Jquery.
$('.year-select').once('current-year').on('change', function () {
var month = $('.month-select');
var currentYear = (new Date()).getFullYear().toString();
var selectedYear = jQuery('.year-select option:selected').val();
if (currentYear === selectedYear) {
var currentMonth = (new Date()).getMonth();
month.find('option').each(function () {
var optionMonth = parseInt($(this).val());
if (optionMonth <= currentMonth) {
if ($(this).is(':selected')) {
$(this).next().prop('selected', true);
}
$(this).prop('disabled', true);
}
});
}
else {
month.find('option').prop('disabled', false);
}
// Let other JS libraries know options are changed.
month.trigger('change');
});
$('.year-select').trigger('change');
// With vanilla javascript.
var yearElement = document.querySelector(".year-select");
yearElement.addEventListener('change', function (event) {
var monthElement = document.querySelector('.month-select');
var currentYear = (new Date()).getFullYear().toString();
var selectedYear = event.target.value;
if (currentYear === selectedYear) {
var currentMonth = (new Date()).getMonth();
[].forEach.call(monthElement.options, function (item) {
var optionMonth = parseInt(item.value);
if (optionMonth <= currentMonth) {
if (item.selected) {
item.nextSibling.selected = true;
}
item.disabled = true;
}
});
}
else {
[].forEach.call(monthElement.options, (item) => item.disabled = false);
}
});
yearElement.dispatchEvent(new Event("change"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment