mister martin
mister martin

Reputation: 6252

Update days based on selected month

I'm trying to write a simple Javascript function to update the days in a select box whenever the month is changed:

/* automatically update days based on month */
function updateMonth(iMonth, iDay) {
    var el = document.getElementById(iDay);
    el.options.length = 0;
    var d = new Date();
    for(i = 0; i < (32 - new Date(d.getFullYear(), iMonth, 32).getDate()); i++) {
        option = new Option(i, i);
        el.options[i] = option;
    }
}

<select name="start_month" id="start_month" onchange="updateMonth(this.value, 'start_day');">
<option>...</option>
</select>
<select name="start_day" id="start_day">
<option>...</option>
</select>
<select name="start_year" id="start_year">
<option>...</option>
</select>

First of all it appears to be updating but I'm getting crazy results. February gives me 30 days, January 27, and they all start with 0? Secondly I'm not sure if I need to consider the year in addition to the month?

Any help understanding this would be greatly appreciated.

http://jsfiddle.net/NK7yd/

Upvotes: 0

Views: 1473

Answers (1)

IvanH
IvanH

Reputation: 5139

Your function should be

window.updateMonth= function(iMonth, iDay) {
    var el = document.getElementById(iDay);
    el.options.length = 0;

    for(var d = new Date(2013,iMonth-1,1); d.getMonth()==iMonth-1; d.setDate(d.getDate()+1)) {
        option = new Option(d.getDate(), d.getDate());
        el.options[d.getDate()-1] = option;
    }; 
}

I is necessary to read value from select with years (instead of hard coded 2013). http://jsfiddle.net/b5XMM/3/

Upvotes: 1

Related Questions