【问题标题】:Jquery - Automatically add current year months to dropdownJquery - 自动将当前年份月份添加到下拉列表
【发布时间】:2017-06-18 09:50:11
【问题描述】:

我正在尝试将当年的当前月份自动添加到 Bootstrap 下拉列表中。

目前,我是手动添加它们,因为我不太擅长 JavaScript。

如何自动将一年中剩余的当前月份添加到列表中?

现在我们在二月它不会添加一月因为它已经过去了。

我已经做了一个引导,所以你可以明白我的意思。

http://www.bootply.com/N2H0BAoapL

【问题讨论】:

    标签: javascript jquery date time twitter-bootstrap-3


    【解决方案1】:

    下面是我的示例,它帮助我在月份的级联下拉列表中显示只有当前年份的有效月份或以前年份的所有月份

    如果选择了 Invalid Year,则下面的示例将禁用 Cascaded Month Drop,并且还将根据年份的选择处理当前的有效月份。

    var currentYear = new Date().getFullYear();
    var currentMonth = new Date().getMonth();
    var cascadedDropDownMonthId = "#dropDownYearMonth";
    
    //Adding Last 10 Years to Year Drop Down
    for (var i = currentYear;i > currentYear - 10 ; i--)
    {
    $("#dropDownYear1").append('<option value="'+ i.toString() +'">' +i.toString() +'</option>');
    }
     
    //Disabling Month Dropdown in case of invalid Selections.
    $(cascadedDropDownMonthId).prop("disabled", true);
    
    $("#dropDownYear1").change(function () {
    
                var currentSelectedValue = $(this).val();
                
                if (currentSelectedValue == "-1")
                {
                    $(cascadedDropDownMonthId).prop("disabled", true);
                }
                else
                {
                    $(cascadedDropDownMonthId).prop("disabled", false);
                    //Get Current Year from Dropdown and Converting to Integer for performing math operations
                    var currentSelectedYear = parseInt($(this).val());
                   
                    //As Index of Javascript Month is from 0 to 11 therefore totalMonths are 11 NOT 12
                    var totalMonths = 11;
                    if (currentSelectedYear == currentYear) {
                        totalMonths = currentMonth;
                    }
                    var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
                    //Emptying the Month Dropdown to clear our last values
                    $(cascadedDropDownMonthId).empty();
                    
                    $(cascadedDropDownMonthId).append('<option value="-1">-Month-</option>');                                
    
                    //Appending Current Valid Months
                    for (var month = 0; month <= totalMonths; month++) {
                        $(cascadedDropDownMonthId).append('<option value="'+ (month+1) +  '">' + monthNames[month] + '</option>');
                    }
                }
        });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
                        
    <select id="dropDownYear1">
        <option value="-1">-Year-</option>
    </select>
    <select id="dropDownYearMonth">
        <option value="-1">-Month-</option>
    </select>

    【讨论】:

      【解决方案2】:

      作为替代方案,在支持 Intl 对象的情况下,月份名称可从 Date.prototype.toLocaleString 获得。这可以采用浏览器默认语言,也可以自己设置。

      请参阅MDN Date.prototype.toLocaleString() 和支持矩阵。我在 IE 10 或更低版本下不工作,但在其他浏览器中有很好的支持。

      例如

      function addRemainingMonthOptions(id, lang) {
      
        // Make sure element exists
        var sel = document.getElementById(id);
        if (!sel) return;
      
        // Get current date, set day to 1 so not affected by adding months
        var d = new Date();
        d.setDate(1);
        
        // Add options until end of year
        do {
          month = d.toLocaleString(lang,{localeMatcher: 'best fit', month:'short'})
          sel.appendChild(new Option(month, month));
          d.setMonth(d.getMonth() +1);
        } while (d.getMonth() > 0)
      }
      
      // Add remaining months in browser default langauge (lang is undefined)
      addRemainingMonthOptions('theMonth0')
      // … in Russian
      addRemainingMonthOptions('theMonth1', 'ru')
      // … in Arabic
      addRemainingMonthOptions('theMonth2', 'ar')
      <select id="theMonth0">
      </select>
      <select id="theMonth1">
      </select>
      <select id="theMonth2">
      </select>

      【讨论】:

        【解决方案3】:

        为此,您可以使用getMonth() 获取当前日期的月份。从那里您可以循环剩余几个月并填充select,如下所示:

        var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
        var month = (new Date()).getMonth();
        for (; month < monthNames.length; month++) {
          $('select').append('<option>' + monthNames[month] + '</option>');
        }
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <select></select>

        这个基本逻辑可以反过来简化为:

        var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
        var html = monthNames.slice((new Date()).getMonth()).map(function(month) {
           return '<option>' + month + '</option>';
        }).join('');
        $('select').html(html);
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <select></select>

        【讨论】:

        • 谢谢罗里,这正是我想要的,谢谢
        • @Rory for (; 是什么意思? (忽略第一个参数)。我只知道
        • @user1673498 没问题,很高兴为您提供帮助
        • @plonknimbuzz 没错——这基本上意味着我不需要在for 中定义迭代变量,因为我可以使用我已经定义的month
        猜你喜欢
        • 2022-12-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多