Reputation: 5603
I have the following code, which returns the number of days in a month:
daysInMonth(month:number, year:number) {
return new Date(year, month, 0).getDate();
}
Let's say this gives me 31
. Now, in my html, I want to create a dropdown
element with all the days in the month, listed out in order. So, my dropdown would consist of:
1,2,3,4,5,6,7,8,9,10,11.....
All the way to 31
.
I need to build this object dynamically since the days in the month will change based on the month.
What's the most efficient way to do that?
Upvotes: 0
Views: 56
Reputation: 10132
You can use the following to achieve the dropdown:
(function() {
var totalDays = daysInMonth(2, 2014),
selectEl = document.createElement('select');
for (var i = 1; i <= totalDays; i++) {
var option = document.createElement('option');
option.appendChild(document.createTextNode(i));
option.setAttribute('value', i);
selectEl.appendChild(option);
}
document.body.appendChild(selectEl);
}());
Upvotes: 0
Reputation: 7456
I would use jQuery.
So somewhere along the line you'd do something:
var dropDown = $('<select/>').appendTo('body');
for (var i = 1; i <= daysOfMonth; i++) {
dropDown.append('<option value=' + i + '>' + i + '</option>');
}
You would clearly need to get the value of daysOfMonth
from somewhere previously.
Upvotes: 1