1

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

Mohammad
  • 21,175
  • 15
  • 55
  • 84
rockdudex
  • 13
  • 3
  • 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 Answers1

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/

Community
  • 1
  • 1
fictus
  • 286
  • 2
  • 5
  • 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
  • i will modify the code in my jsfiddle in a few minutes – fictus Jun 24 '16 at 00:24
  • 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