Repopulating dates on select boxes

后端 未结 2 376
孤街浪徒
孤街浪徒 2021-01-12 21:58

I\'ve created a date_select in Rails (which is 3 select boxes: one for year, one for month, and one for day).

To have 31st February on them is quite confusing. What

2条回答
  •  北海茫月
    2021-01-12 22:41

    I assume you have three selects with classes 'day', 'month', 'year'. Then use this JS:

    function monthChanged() {
        var days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
        var month = $('.month').val() - 1, year = +$('.year').val();
        var diff;
    
        // Check for leap year if Feb
        if (month == 1 && new Date(year, month, 29).getMonth() == 1) days[1]++;
    
        // Add/Remove options
        diff = $('.day option').length - (days[month] + 1);
        if (diff > 0) { // Remove
            $('.day option').slice(days[month] + 1).remove();
        } else if (diff < 0) { // Add
            for (var i = $('.day option').length; i <= days[month]; i++) {
                $('

    Demo: http://jsfiddle.net/FxBpB/

提交回复
热议问题