Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use jQuery on HTML Select Menu for Birthday/Date of Birth format

I'm looking to have a standard HTML select menu for selecting your date of birth. Day, Month, Year. Can someone point me in the right direction to use jQuery to format the correct number of days in the month depending on what year / month is selected etc? Are there any plugins out there to achieve this, or how would I write this myself? Any advice would be appreciated.

like image 976
Chris Avatar asked Sep 19 '13 17:09

Chris


1 Answers

basically you need three select boxes (day, month, year) with onchange events on year and month.

changes on the year and month select box need to update the number of days because these depend on year and month. to calculate the number of days for a given month/year, this article will be helpful.

http://www.electrictoolbox.com/javascript-days-in-month/

working example JSFIDDLE

html

<select id="days"></select>
<select id="months"></select>
<select id="years"></select>

js

$(function() {

    //populate our years select box
    for (i = new Date().getFullYear(); i > 1900; i--){
        $('#years').append($('<option />').val(i).html(i));
    }
    //populate our months select box
    for (i = 1; i < 13; i++){
        $('#months').append($('<option />').val(i).html(i));
    }
    //populate our Days select box
    updateNumberOfDays(); 

    //"listen" for change events
    $('#years, #months').change(function(){
        updateNumberOfDays(); 
    });

});

//function to update the days based on the current values of month and year
function updateNumberOfDays(){
    $('#days').html('');
    month = $('#months').val();
    year = $('#years').val();
    days = daysInMonth(month, year);

    for(i=1; i < days+1 ; i++){
            $('#days').append($('<option />').val(i).html(i));
    }
}

//helper function
function daysInMonth(month, year) {
    return new Date(year, month, 0).getDate();
}
like image 139
kasper Taeymans Avatar answered Sep 21 '22 12:09

kasper Taeymans