【问题标题】:Repopulating dates on select boxes重新填充选择框上的日期
【发布时间】:2011-01-27 22:15:01
【问题描述】:

我在 Rails 中创建了一个 date_select(这是 3 个选择框:一个用于年份,一个用于月份,一个用于日期)。

2 月 31 日在他们身上是相当令人困惑的。我希望能够使选择框仅具有有效日期。我的意思是,当您选择 2 月、31 日、30 日(以及某些年份的 29 日)时,它们会被删除,然后,当您选择 1 月时,它们会被再次添加,依此类推。此外,我希望初始选择框仅填充所选月份的日期。

【问题讨论】:

  • 我会在那里放一点 jquery。

标签: javascript jquery ruby-on-rails ruby-on-rails-3


【解决方案1】:

我假设您有三个类别为'day', 'month', 'year' 的选择。 然后使用这个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++) {
            $('<option>').attr('value', i).text(i).appendTo('.day');
        }
    }
}

$(function () {
    monthChanged(); // On document ready
    $('.month').change(monthChanged); // On month change
    $('.year').change(monthChanged); // On year change (for leap years)
});

演示:http://jsfiddle.net/FxBpB/

【讨论】:

  • 您能帮我解决这个问题吗?谢谢:)
  • @Rolpege,你需要一个 div 来包裹每组 3 个选择,并给那个 div 一个类,比如“日期”,然后使用 .closest("date").find(".month") 而不是直接选择 ".month" .查看closest 文档:api.jquery.com/closest
  • 这感觉像是一个常见的“问题”,我很惊讶没有 jQuery 插件。你有没有想过把它包装成一个插件并发布它?
  • 如果你做插件化这个,你可以使用这个技巧来减少大小以获得一个月中的天数:electrictoolbox.com/javascript-days-in-month
【解决方案2】:
/* automatically update days based on month */

for (var i = 2014; i < 2019; i++) {
    $('<option>').attr('value', i).text(i).appendTo('#start_year');
}

function monthChanged() {
    debugger;
    var days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    var month = $('#start_month').val() - 1,
        year = +$('#start_year').val();

    // Check for leap year if Feb
    if (month == 1 && new Date(year, month, 29).getMonth() == 1) 
        days[1]++;

    // Add/Remove options
    if ($('#start_day option').length > days[month]) {
        // Remove
        $('#start_day option').slice(days[month] + 1).remove();
    } else if ($('#start_day option').length < days[month] + 1) {
        // Add
        for (var i = $('#start_day option').length + 1; i <= days[month]; i++) {
            $('<option>').attr('value', i).text(i).appendTo('#start_day');
        }
    }
}


monthChanged(); // On document ready
$('#start_month').change(monthChanged); // On month change
$('#start_year').change(monthChanged); // On year change (for leap years)

参考小提琴链接:http://jsfiddle.net/u3fr1mt0/

【讨论】:

  • 检查上面的代码以避免在下拉列表中重复日期。(日期 2nd 显示两次)
  • 你真的应该提到这是另一个答案的改进版本。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
  • 2011-09-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多