سؤال

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.

هل كانت مفيدة؟

المحلول

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();
}

نصائح أخرى

The jQuery UI library has an excellent and highly tailorable widget called a date picker. The page for the widget, as well as the code you can use as a reference can all be found here: http://jqueryui.com/datepicker/

All you need is to include jQuery and the jQuery UI libraries like so in your header:

<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>

Then, create a normal textbox:

<input name="Date" id="Date" value="" />

And then initialize the date picker using the following code:

<script type="text/javascript">

    $(function() {
        $("#Date").datepicker({
            changeMonth: true,
            changeYear: true
            });
    };

</script>

The options I put on the datepicker widget allow you to easily jump to a given month/year as will be needed for anyone born several years ago.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top