I'm quite new to web development and though I know I can use those calendar datepickers to input dates to a a form. I was wondering how can I hide or disable incorrect days from day-month-year
droplists, like 30 february
or 31 april
. Is there a non obscure way to do that using javascript or jquery?
I'm thinking on this kind of datepicker.
See jsfiddle
Asked
Active
Viewed 42 times
1
-
You can force the user to select a month first, and update the values which are enabled for the day picker. Then once a year is selected, you can run some date validation (http://stackoverflow.com/questions/1353684/detecting-an-invalid-date-date-instance-in-javascript) to determine whether or not it is a valid date, to then inform the user that the date is invalid – Adjit Jun 23 '16 at 18:00
1 Answers
0
Based on the answer from HERE, first add a few more classes to your drop-down lists and use JQuery this way:
$(document).ready(function () {
$('.operator').on('change', function () {
var daysx = Math.round(((new Date($('.year option:selected').val(), $('.month option:selected').val()))-(new Date($('.year option:selected').val(), parseInt($('.month option:selected').val())-1)))/86400000);
console.log(daysx);
$('.maindates option').remove();
for (var i=1; i < (daysx + 1); i++) {
$('.maindates').append('<option value="' + i + '">' + i + '</option>');
}
});
});
See my jsfiddle here: http://jsfiddle.net/fictus/2gc28dcd/
-
that did the trick wonderfully. thank you very much. but I noticed that whenever you click a diferent month or year of the list the value of the day goes back to 1 (naturally because it creates the correct array for the month, I think). ehm how could we get around that issue?. (I knew I had to tackle jquery before college.) – rockdudex Jun 23 '16 at 23:15
-
-
Ok, I modified the jsfiddle. view it again and copy the changes here: [https://jsfiddle.net/fictus/2gc28dcd/](https://jsfiddle.net/fictus/2gc28dcd/) – fictus Jun 24 '16 at 00:43
-
Just updated again. I added an if statement to select the last available date of the month in case you previously selected a greater date and said date is no longer available after changing the month or year. – fictus Jun 24 '16 at 00:58