Skip to content
Advertisement

Populate dropdown list with current day, month and year

I am probably asking an easy question for you, but I am still a newbie, so please someone help me. I have this html and jQuery code:

JavaScript
JavaScript

So the question is: How can I populate one more dropdown showing current day, but also showing all the days from the month, based on if they are 30, 31, 28 or even leap year (29 days in Fevruary)? Any help will be appreciated. P.S. And also can this be done more dynamically ?

Advertisement

Answer

Well, instead of writing a lot of options tag, why not let a loop do it for you… check my code below please, I’ll give a brief explanation below that.

(This code uses jQuery, but it is easily achievable with vanilla JS)

JavaScript
JavaScript

There’s a variable called qntYears, there you set how many years back from current year you want to show in the select of years…

after that, there’s a loop adding all months, nothing special here.

The last part is the important one, I added a change callback to the selects of year and month. When they change, the listener recreates (using a for loop) the days based on the year and current month, it is very useful since every month has different amount of days (28, 29, 30, 31).
The function that do this is the AdjustDays().

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement