簡體   English   中英

jQuery UI DatePicker 只顯示月份和年份

[英]jQuery UI DatePicker to show month year only

我正在使用 jQuery 日期選擇器在我的應用程序中顯示日歷。 我想知道我是否可以用它來顯示月份和年份(2010 年 5 月)而不是日歷?

這是一個 hack(更新了整個 .html 文件):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
    <link rel="stylesheet" type="text/css" media="screen" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/jquery-ui.css">
    <script type="text/javascript">
        $(function() {
            $('.date-picker').datepicker( {
            changeMonth: true,
            changeYear: true,
            showButtonPanel: true,
            dateFormat: 'MM yy',
            onClose: function(dateText, inst) { 
                $(this).datepicker('setDate', new Date(inst.selectedYear, inst.selectedMonth, 1));
            }
            });
        });
    </script>
    <style>
    .ui-datepicker-calendar {
        display: none;
    }
    </style>
</head>
<body>
    <label for="startDate">Date :</label>
    <input name="startDate" id="startDate" class="date-picker" />
</body>
</html>

編輯jsfiddle 上面的例子: http : //jsfiddle.net/DBpJe/7755/

編輯 2僅在單擊完成按鈕時將月年值添加到輸入框。 還允許刪除輸入框值,這在上述字段中是不可能的http://jsfiddle.net/DBpJe/5103/

EDIT 3基於 rexwolf 的解決方案更新了更好的解決方案。
http://jsfiddle.net/DBpJe/5106

這段代碼對我來說完美無缺:

<script type="text/javascript">
$(document).ready(function()
{   
    $(".monthPicker").datepicker({
        dateFormat: 'MM yy',
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,

        onClose: function(dateText, inst) {
            var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
            var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
            $(this).val($.datepicker.formatDate('MM yy', new Date(year, month, 1)));
        }
    });

    $(".monthPicker").focus(function () {
        $(".ui-datepicker-calendar").hide();
        $("#ui-datepicker-div").position({
            my: "center top",
            at: "center bottom",
            of: $(this)
        });
    });
});
</script>

<label for="month">Month: </label>
<input type="text" id="month" name="month" class="monthPicker" />

輸出是:

在此處輸入圖片說明

@Ben Koehler ,太棒了! 我做了一個小的修改,以便多次使用日期選擇器的單個實例按預期工作。 如果沒有此修改,日期將被錯誤解析,並且不會突出顯示先前選擇的日期。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
    <link rel="stylesheet" type="text/css" media="screen" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/jquery-ui.css">
    <script type="text/javascript">
    $(function() {
        $('.date-picker').datepicker( {
            changeMonth: true,
            changeYear: true,
            showButtonPanel: true,
            dateFormat: 'MM yy',
            onClose: function(dateText, inst) { 
                var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
                var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
                $(this).datepicker('setDate', new Date(year, month, 1));
            },
            beforeShow : function(input, inst) {
                var datestr;
                if ((datestr = $(this).val()).length > 0) {
                    year = datestr.substring(datestr.length-4, datestr.length);
                    month = jQuery.inArray(datestr.substring(0, datestr.length-5), $(this).datepicker('option', 'monthNamesShort'));
                    $(this).datepicker('option', 'defaultDate', new Date(year, month, 1));
                    $(this).datepicker('setDate', new Date(year, month, 1));
                }
            }
        });
    });
    </script>
    <style>
    .ui-datepicker-calendar {
        display: none;
        }
    </style>
</head>
<body>
    <label for="startDate">Date :</label>
    <input name="startDate" id="startDate" class="date-picker" />
</body>
</html>

上面的回答都很好。 我唯一的抱怨是,一旦設置了該值,您就無法清除它。 我也更喜歡擴展 jquery-like-a-plugin 方法。

這對我來說很完美:

$.fn.monthYearPicker = function(options) {
    options = $.extend({
        dateFormat: "MM yy",
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        showAnim: ""
    }, options);
    function hideDaysFromCalendar() {
        var thisCalendar = $(this);
        $('.ui-datepicker-calendar').detach();
        // Also fix the click event on the Done button.
        $('.ui-datepicker-close').unbind("click").click(function() {
            var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
            var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
            thisCalendar.datepicker('setDate', new Date(year, month, 1));
        });
    }
    $(this).datepicker(options).focus(hideDaysFromCalendar);
}

然后像這樣調用:

$('input.monthYearPicker').monthYearPicker();
<style>
.ui-datepicker table{
    display: none;
}

<script type="text/javascript">
$(function() {
    $( "#manad" ).datepicker({
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        dateFormat: 'yy-mm',
        onClose: function(dateText, inst) { 
            var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
            var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
            $(this).datepicker('setDate', new Date(year, month, 1));
        },
        beforeShow : function(input, inst) {
            if ((datestr = $(this).val()).length > 0) {
                actDate = datestr.split('-');
                year = actDate[0];
                month = actDate[1]-1;
                $(this).datepicker('option', 'defaultDate', new Date(year, month));
                $(this).datepicker('setDate', new Date(year, month));
            }
        }
    });
});

這將解決問題 =) 但我想要 timeFormat yyyy-mm

雖然只在FF4中嘗試過

我今天也有同樣的需求,並在 github 上找到了它,使用 jQueryUI 並使用月份選擇器代替日歷中的日期

https://github.com/thebrowser/jquery.ui.monthpicker

這是我想出的。 它隱藏了日歷,不需要額外的樣式塊,並添加了一個清除按鈕來處理點擊輸入后無法清除值的問題。 也可以很好地與同一頁面上的多個月份選擇器一起使用。

HTML:

<input type='text' class='monthpicker'>

JavaScript:

$(".monthpicker").datepicker({
    changeMonth: true,
    changeYear: true,
    dateFormat: "yy-mm",
    showButtonPanel: true,
    currentText: "This Month",
    onChangeMonthYear: function (year, month, inst) {
        $(this).val($.datepicker.formatDate('yy-mm', new Date(year, month - 1, 1)));
    },
    onClose: function(dateText, inst) {
        var month = $(".ui-datepicker-month :selected").val();
        var year = $(".ui-datepicker-year :selected").val();
        $(this).val($.datepicker.formatDate('yy-mm', new Date(year, month, 1)));
    }
}).focus(function () {
    $(".ui-datepicker-calendar").hide();
}).after(
    $("<a href='javascript: void(0);'>clear</a>").click(function() {
        $(this).prev().val('');
    })
);

像許多其他人一樣,我在嘗試執行此操作時遇到了許多問題,並且只有發布的解決方案的組合,以及最終使其完美的大黑客,為我提供了一個適用於所有日期格式和本地化解決方案,就像普通日期選擇器。

我嘗試過的該線程中其他解決方案的問題:

  1. 在日期選擇器中選擇一個新日期,也會更改其他日期選擇器的(內部)日期,因此當您再次打開其他日期選擇器(或嘗試獲取它們的日期)時,它們的日期將與其分配的輸入中顯示的日期不同-場地。
  2. 日期選擇器在再次打開時不會“記住”日期。
  3. 處理日期的代碼使用子串,因此它與所有格式都不兼容。
  4. 如果您為日期輸入格式錯誤的輸入字符串,然后在日期選擇器上單擊“關閉”,則輸入字段未正確更新。
  5. 月份選擇器僅在關閉時更改輸入字段,而不是在值更改時更改。
  6. 您不能在與不顯示日期的月份選擇器相同的頁面上使用顯示日期的普通日期選擇器。

我終於找到了解決所有這些問題的方法,即使是在原來的日期選擇器中!

注意:您不需要使用以下monthpicker 腳本來修復普通jQuery datepickers 中的前四個問題。 只需使用本文后面的Datepicker 實例化腳本即可。 問題 5 和問題 6 僅與我嘗試過的不同月份選擇器解決方案有關。

問題 1-3 和 5 與如何在其內部代碼中引用日期和月份選擇器有關,確保它們不會干擾其他日期和月份選擇器,以及選擇器的一些手動更新。 您可以在下面的實例化示例中看到這一點。 通過向 datepicker 函數添加一些自定義代碼來修復第四個問題(參見示例中的注釋,尤其是關於 onClose)。

對於第六個也是最后一個問題,僅與datepickers 一起使用monthpickers 相關,我們只需要正確分離 datepickers 和 monthpickers 。

那么,為什么不獲取為數不多的自定義 jQuery-UI 月份選擇器插件之一呢? 我在寫這篇文章時發現的那些缺乏本地化靈活性/能力,有些缺乏動畫支持......所以,該怎么辦? 從日期選擇器代碼中滾動您的“自己的”! 這為您提供了一個功能齊全的月份選擇器,具有日期選擇器的所有功能,只是不顯示天數。

我提供了一個monthpicker js-script隨附的 CSS-script ,使用下面描述的方法,以及 jQuery-UI v1.11.1 代碼。 只需將這些代碼片段分別復制到兩個新文件:monthpicker.js 和 monthpicker.css。

如果您想了解我將 datepicker 轉換為 monthpicker的相當簡單的過程,請向下滾動到最后一部分。 然后,您也許可以使用較新版本的 jQuery-UI 重復該過程。


現在將日期選擇器和月份選擇器添加到頁面!

以下這些 javascript 代碼片段與頁面上的多個日期選擇器和/或月份選擇器一起使用,沒有上述問題! 通常通過使用“$(this)”來修復。 很多 :)

第一個腳本用於普通日期選擇器,第二個腳本用於“新”月份選擇器。

注釋掉的.after可讓您創建一些元素來清除輸入字段,這是從 Paul Richards 的回答中竊取的。

我在我的月份選擇器中使用“MM yy”格式,在我的日期選擇器中使用“yy-mm-dd”格式,但這與所有格式完全兼容,因此您可以隨意使用任何一種格式 只需更改 'dateFormat' 選項。 標准選項“showButtonPanel”、“showAnim”和“yearRange”當然是可選的,可以根據您的意願進行定制。


添加日期選擇器

日期選擇器實例化。 這個從 90 年前到現在。 它可以幫助您保持輸入字段正確,特別是如果您設置了 defaultDate、minDate 和 maxDate 選項,但如果您不這樣做,它可以處理它。 它適用於您選擇的任何日期格式。

        $('#MyDateTextBox').datepicker({
            dateFormat: 'yy-mm-dd',
            changeMonth: true,
            changeYear: true,
            showButtonPanel: true,
            showMonthAfterYear: true,
            showWeek: true,
            showAnim: "drop",
            constrainInput: true,
            yearRange: "-90:",
            minDate: new Date((new Date().getFullYear() - 90), new Date().getMonth(), new Date().getDate()),
            maxDate: new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()),
            defaultDate: new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()),
            
            onClose: function (dateText, inst) {
                // When onClose is called after we have clicked a day (and not clicked 'Close' or outside the datepicker), the input-field is automatically
                // updated with a valid date-string. They will always pass, because minDate and maxDate are already enforced by the datepicker UI.
                // This try is to catch and handle the situations, where you open the datepicker, and manually type in an invalid date in the field,
                // and then close the datepicker by clicking outside the datepicker, or click 'Close', in which case no validation takes place.
                try {
                    // If datepicker can parse the date using our formatstring, the instance will automatically parse
                    // and apply it for us (after the onClose is done).
                    // If the input-string is invalid, 'parseDate' will throw an exception, and go to our catch.
                    // If the input-string is EMPTY, then 'parseDate' will NOT throw an exception, but simply return null!
                    var typedDate = $.datepicker.parseDate($(this).datepicker('option', 'dateFormat'), $(this).val());

                    // typedDate will be null if the entered string is empty. Throwing an exception will force the datepicker to
                    // reset to the last set default date.
                    // You may want to just leave the input-field empty, in which case you should replace 'throw "No date selected";' with 'return;'
                    if (typedDate == null)throw "No date selected";

                    // We do a manual check to see if the date is within minDate and maxDate, if they are defined.
                    // If all goes well, the default date is set to the new date, and datepicker will apply the date for us.
                    var minDate = $(this).datepicker("option", "minDate");
                    var maxDate = $(this).datepicker("option", "maxDate");
                    if (minDate !== null && typedDate < minDate) throw "Date is lower than minDate!";
                    if (maxDate !== null && typedDate > maxDate) throw "Date is higher than maxDate!";

                    // We update the default date, because the date seems valid.
                    // We do not need to manually update the input-field, as datepicker has already done this automatically.
                    $(this).datepicker('option', 'defaultDate', typedDate);
                }
                catch (err) {
                    console.log("onClose: " + err);
                    // Standard behavior is that datepicker does nothing to fix the value of the input field, until you choose
                    // a new valid date, by clicking on a day.
                    // Instead, we set the current date, as well as the value of the input-field, to the last selected (and
                    // accepted/validated) date from the datepicker, by getting its default date. This only works, because
                    // we manually change the default date of the datepicker whenever a new date is selected, in both 'beforeShow'
                    // and 'onClose'.
                    var date = $(this).datepicker('option', 'defaultDate');
                    $(this).val($.datepicker.formatDate($(this).datepicker('option', 'dateFormat'), date));
                    $(this).datepicker('setDate', date);
                }
            },

            beforeShow: function (input, inst) {
                // beforeShow is particularly irritating when initializing the input-field with a date-string.
                // The date-string will be parsed, and used to set the currently selected date in the datepicker.
                // BUT, if it is outside the scope of the minDate and maxDate, the text in the input-field is not
                // automatically updated, only the internal selected date, until you choose a new date (or, because
                // of our onClose function, whenever you click close or click outside the datepicker).
                // We want the input-field to always show the date that is currently chosen in our datepicker,
                // so we do some checks to see if it needs updating. This may not catch ALL cases, but these are
                // the primary ones: invalid date-format; date is too early; date is too late.
                try {
                    // If datepicker can parse the date using our formatstring, the instance will automatically parse
                    // and apply it for us (after the onClose is done).
                    // If the input-string is invalid, 'parseDate' will throw an exception, and go to our catch.
                    // If the input-string is EMPTY, then 'parseDate' will NOT throw an exception, but simply return null!
                    var typedDate = $.datepicker.parseDate($(this).datepicker('option', 'dateFormat'), $(this).val());

                    // typedDate will be null if the entered string is empty. Throwing an exception will force the datepicker to
                    // reset to the last set default date.
                    // You may want to just leave the input-field empty, in which case you should replace 'throw "No date selected";' with 'return;'
                    if (typedDate == null)throw "No date selected";

                    // We do a manual check to see if the date is within minDate and maxDate, if they are defined.
                    // If all goes well, the default date is set to the new date, and datepicker will apply the date for us.
                    var minDate = $(this).datepicker("option", "minDate");
                    var maxDate = $(this).datepicker("option", "maxDate");
                    if (minDate !== null && typedDate < minDate) throw "Date is lower than minDate!";
                    if (maxDate !== null && typedDate > maxDate) throw "Date is higher than maxDate!";

                    // We update the input-field, and the default date, because the date seems valid.
                    // We also manually update the input-field, as datepicker does not automatically do this when opened.
                    $(this).val($.datepicker.formatDate($(this).datepicker('option', 'dateFormat'), typedDate));
                    $(this).datepicker('option', 'defaultDate', typedDate);
                }
                catch (err) {
                    // Standard behavior is that datepicker does nothing to fix the value of the input field, until you choose
                    // a new valid date, by clicking on a day.
                    // We want the same behavior when opening the datepicker, so we set the current date, as well as the value
                    // of the input-field, to the last selected (and accepted/validated) date from the datepicker, by getting
                    // its default date. This only works, because we manually change the default date of the datepicker whenever
                    // a new date is selected, in both 'beforeShow' and 'onClose', AND have a default date set in the datepicker options.
                    var date = $(this).datepicker('option', 'defaultDate');
                    $(this).val($.datepicker.formatDate($(this).datepicker('option', 'dateFormat'), date));
                    $(this).datepicker('setDate', date);
                }
            }
        })
    //.after( // this makes a link labeled "clear" appear to the right of the input-field, which clears the text in it
    //    $("<a href='javascript: void(0);'>clear</a>").click(function() {
    //        $(this).prev().val('');
    //    })
    //)
    ;

添加月份選擇器

在要使用月份選擇器的頁面中包含 monthpicker.js 文件和 monthpicker.css 文件。

Monthpicker 實例化從此月選擇器檢索的值始終是所選月份的第一天。 從當月開始,范圍從 100 年前到未來 10 年。

    $('#MyMonthTextBox').monthpicker({
        dateFormat: 'MM yy',
        changeMonth: true,
        changeYear: true,
        showMonthAfterYear: true,
        showAnim: "drop",
        constrainInput: true,
        yearRange: "-100Y:+10Y",
        minDate: new Date(new Date().getFullYear() - 100, new Date().getMonth(), 1),
        maxDate: new Date((new Date().getFullYear() + 10), new Date().getMonth(), 1),
        defaultDate: new Date(new Date().getFullYear(), new Date().getMonth(), 1),
        
        // Monthpicker functions
        onClose: function (dateText, inst) {
            var date = new Date(inst.selectedYear, inst.selectedMonth, 1);
            $(this).monthpicker('option', 'defaultDate', date);
            $(this).monthpicker('setDate', date);
        },

        beforeShow: function (input, inst) {
            if ($(this).monthpicker("getDate") !== null) {
                // Making sure that the date set is the first of the month.
                if($(this).monthpicker("getDate").getDate() !== 1){
                    var date = new Date(inst.selectedYear, inst.selectedMonth, 1);
                    $(this).monthpicker('option', 'defaultDate', date);
                    $(this).monthpicker('setDate', date);
                }
            } else {
                // If the date is null, we reset it to the defaultDate. Make sure that the defaultDate is always set to the first of the month!
                $(this).monthpicker('setDate', $(this).monthpicker('option', 'defaultDate'));
            }
        },
        // Special monthpicker function!
        onChangeMonthYear: function (year, month, inst) {
            $(this).val($.monthpicker.formatDate($(this).monthpicker('option', 'dateFormat'), new Date(year, month - 1, 1)));
        }
    })
    //.after( // this makes a link labeled "clear" appear to the right of the input-field, which clears the text in it
    //    $("<a href='javascript: void(0);'>clear</a>").click(function() {
    //        $(this).prev().val('');
    //    })
    //)
    ;

就是這樣! 這就是制作月份選擇器所需的全部內容。

我似乎無法讓 jsfiddle 使用它,但它在我的 ASP.NET MVC 項目中對我有用。 只需執行您通常所做的將日期選擇器添加到您的頁面,並合並上述腳本,可能通過將選擇器(意思是 $("#MyMonthTextBox"))更改為適合您的內容。

我希望這可以幫助別人。

一些額外的日期和月份選擇器設置的粘貼箱鏈接:

  1. Monthpicker 在本月的最后一天工作 您從此月選擇器獲得的日期將始終是該月的最后一天。

  2. 兩個合作的月份選擇器 “開始”在本月的第一天工作,“結束”在本月的最后一天工作。 它們都相互限制,因此在“開始”所選月份之前選擇“結束”月份,會將“開始”更改為與“結束”相同的月份。 反之亦然。 可選:在“開始”上選擇月份時,“結束”上的“minDate”將設置為該月。 要刪除此功能,請在 onClose 中注釋掉一行(閱讀注釋)。

  3. 兩個協作日期選擇器 它們都相互限制,因此在“開始”所選日期之前選擇“結束”日期,會將“開始”更改為與“結束”相同的月份。 反之亦然。 可選:在“開始”上選擇日期時,“結束”上的“minDate”將設置為該日期。 要刪除此功能,請在 onClose 中注釋掉一行(閱讀注釋)。


我如何將 DatePicker 更改為 MonthPicker

我已經從 jquery-ui-1.11.1.js 中獲取了與他們的日期選擇器相關的所有 javascript 代碼,將其粘貼到一個新的 js 文件中,並替換了以下字符串:

  • “日期選擇器”==>“月份選擇器”
  • “日期選擇器”==>“月份選擇器”
  • “日期選擇器”==>“月份選擇器”
  • “日期選擇器”==>“月份選擇器”

然后我刪除了 for 循環的一部分,它創建了整個 ui-datepicker-calendar div(其他解決方案使用 CSS 隱藏的 div)。 這可以在 _generateHTML: 函數 (inst) 中找到。

找到說:

"</div><table class='ui-datepicker-calendar'><thead>" +

標記從關閉 div 標簽之后到(包括)它說的行的所有內容:

drawMonth++;

現在它會不高興,因為我們需要關閉一些東西。 在關閉之前的 div-tag 之后,添加以下內容:

";

代碼現在應該很好地縫合在一起。 這是一個代碼片段,顯示了您應該得到的結果:

...other code...

calender += "<div class='ui-monthpicker-header ui-widget-header ui-helper-clearfix" + cornerClass + "'>" +
                (/all|left/.test(cornerClass) && row === 0 ? (isRTL ? next : prev) : "") +
                (/all|right/.test(cornerClass) && row === 0 ? (isRTL ? prev : next) : "") +
                this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate,
                    row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers
                "</div>";
            drawMonth++;
            if (drawMonth > 11) {
                drawMonth = 0;
                drawYear++;
            }

...other code...

然后我將 jquery-ui.css 中與日期選擇器相關的代碼復制/粘貼到一個新的 CSS 文件中,並替換了以下字符串:

  • “日期選擇器”==>“月份選擇器”

添加一個更簡單的解決方案

 $(function() {
    $('.monthYearPicker').datepicker({
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        dateFormat: 'M yy'
    }).focus(function() {
        var thisCalendar = $(this);
        $('.ui-datepicker-calendar').detach();
        $('.ui-datepicker-close').click(function() {
var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
thisCalendar.datepicker('setDate', new Date(year, month, 1));
        });
    });
});

http://jsfiddle.net/tmnasim/JLydp/
特點

  • 只顯示月/年
  • 僅在單擊“完成”按鈕時將月年值添加到輸入框
  • 單擊“完成”時沒有“重新打開”行為
    ---------------------
    另一個適用於同一頁面中的datepicker和monthpicker的解決方案:(也避免了IE中多次單擊上一個按鈕的錯誤,如果我們使用焦點功能可能會出現這種錯誤)
    JS小提琴鏈接

I needed a Month/Year picker for two fields (From & To) and when one was chosen the Max/Min was set on the other one...a la picking airline ticket dates. 我在設置最大值和最小值時遇到問題……另一個字段的日期會被刪除。 感謝上面的幾個帖子......我終於想通了。 您必須以非常特定的順序設置選項和日期。

有關完整解決方案,請參閱此小提琴: Month/Year Picker @ JSFiddle

代碼:

var searchMinDate = "-2y";
var searchMaxDate = "-1m";
if ((new Date()).getDate() <= 5) {
    searchMaxDate = "-2m";
}
$("#txtFrom").datepicker({
    dateFormat: "M yy",
    changeMonth: true,
    changeYear: true,
    showButtonPanel: true,
    showAnim: "",
    minDate: searchMinDate,
    maxDate: searchMaxDate,
    showButtonPanel: true,
    beforeShow: function (input, inst) {
        if ((datestr = $("#txtFrom").val()).length > 0) {
            var year = datestr.substring(datestr.length - 4, datestr.length);
            var month = jQuery.inArray(datestr.substring(0, datestr.length - 5), "#txtFrom").datepicker('option', 'monthNamesShort'));
        $("#txtFrom").datepicker('option', 'defaultDate', new Date(year, month, 1));
                $("#txtFrom").datepicker('setDate', new Date(year, month, 1));
            }
        },
        onClose: function (input, inst) {
            var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
            var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
            $("#txtFrom").datepicker('option', 'defaultDate', new Date(year, month, 1));
            $("#txtFrom").datepicker('setDate', new Date(year, month, 1));
            var to = $("#txtTo").val();
            $("#txtTo").datepicker('option', 'minDate', new Date(year, month, 1));
            if (to.length > 0) {
                var toyear = to.substring(to.length - 4, to.length);
                var tomonth = jQuery.inArray(to.substring(0, to.length - 5), $("#txtTo").datepicker('option', 'monthNamesShort'));
                $("#txtTo").datepicker('option', 'defaultDate', new Date(toyear, tomonth, 1));
                $("#txtTo").datepicker('setDate', new Date(toyear, tomonth, 1));
            }
        }
    });
    $("#txtTo").datepicker({
        dateFormat: "M yy",
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        showAnim: "",
        minDate: searchMinDate,
        maxDate: searchMaxDate,
        showButtonPanel: true,
        beforeShow: function (input, inst) {
            if ((datestr = $("#txtTo").val()).length > 0) {
                var year = datestr.substring(datestr.length - 4, datestr.length);
                var month = jQuery.inArray(datestr.substring(0, datestr.length - 5), $("#txtTo").datepicker('option', 'monthNamesShort'));
                $("#txtTo").datepicker('option', 'defaultDate', new Date(year, month, 1));
                $("#txtTo").datepicker('setDate', new Date(year, month, 1));
            }
        },
        onClose: function (input, inst) {
            var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
            var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
            $("#txtTo").datepicker('option', 'defaultDate', new Date(year, month, 1));
            $("#txtTo").datepicker('setDate', new Date(year, month, 1));
            var from = $("#txtFrom").val();
            $("#txtFrom").datepicker('option', 'maxDate', new Date(year, month, 1));
            if (from.length > 0) {
                var fryear = from.substring(from.length - 4, from.length);
                var frmonth = jQuery.inArray(from.substring(0, from.length - 5), $("#txtFrom").datepicker('option', 'monthNamesShort'));
                $("#txtFrom").datepicker('option', 'defaultDate', new Date(fryear, frmonth, 1));
                $("#txtFrom").datepicker('setDate', new Date(fryear, frmonth, 1));
            }

        }
    });

如上所述,還將其添加到樣式塊中:

.ui-datepicker-calendar { display: none !important; }

我結合了上述許多好的答案並得出以下結論:

    $('#payCardExpireDate').datepicker(
            {
                dateFormat: "mm/yy",
                changeMonth: true,
                changeYear: true,
                showButtonPanel: true,
                onClose: function(dateText, inst) { 
                    var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
                    var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
                    $(this).datepicker('setDate', new Date(year, month, 1)).trigger('change');
                },
                beforeShow : function(input, inst) {
                    if ((datestr = $(this).val()).length > 0) {
                        year = datestr.substring(datestr.length-4, datestr.length);
                        month = datestr.substring(0, 2);
                        $(this).datepicker('option', 'defaultDate', new Date(year, month-1, 1));
                        $(this).datepicker('setDate', new Date(year, month-1, 1));
                    }
                }
            }).focus(function () {
                $(".ui-datepicker-calendar").hide();
                $("#ui-datepicker-div").position({
                    my: "center top",
                    at: "center bottom",
                    of: $(this)
                });
            });

這被證明是有效的,但面臨許多錯誤,所以我被迫在 datepicker 的幾個地方打補丁:

if($.datepicker._get(inst, "dateFormat") === "mm/yy")
{
    $(".ui-datepicker-calendar").hide();
}

patch1:在 _showDatepicker 中:平滑隱藏;

patch2: in _checkOffset: 修正月份選擇器定位(否則當字段在瀏覽器底部時,偏移檢查關閉);

patch3:在 _hideDatepicker 的 onClose 中:否則關閉日期字段時會閃爍很短的時間,這很煩人。

我知道我的修復還遠遠不夠好,但現在它正在起作用。 希望能幫助到你。

如果你正在尋找一個月選擇器試試這個jquery.mtz.monthpicker

這對我很有效。

options = {
    pattern: 'yyyy-mm', // Default is 'mm/yyyy' and separator char is not mandatory
    selectedYear: 2010,
    startYear: 2008,
    finalYear: 2012,
    monthNames: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
};

$('#custom_widget').monthpicker(options);

是只有我還是這在 IE(8) 中不能正常工作? 單擊完成時日期會發生變化,但日期選擇器會再次打開,直到您實際單擊頁面中的某個位置以松開對輸入字段的關注...

我正在尋找解決這個問題。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
    <link rel="stylesheet" type="text/css" media="screen" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/jquery-ui.css">
<script type="text/javascript">
$(function() {
    $('.date-picker').datepicker( {
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        dateFormat: 'MM yy',
        onClose: function(dateText, inst) { 
            var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
            var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
            $(this).datepicker('setDate', new Date(year, month, 1));
        }
    });
});
</script>
<style>
.ui-datepicker-calendar {
    display: none;
    }
</style>
</head>
<body>
    <label for="startDate">Date :</label>
    <input name="startDate" id="startDate" class="date-picker" />
</body>
</html>

在為 datepicker 挖掘 jQueryUI.com 之后,這是我的結論和對您問題的回答。

首先,我說你的問題。 您不能僅使用 jQueryUI datepicker 來選擇月份和年份。 不支持。 它沒有回調函數。

但是您可以通過使用 css 隱藏日期等來破解它以僅顯示月份和年份。我認為仍然沒有意義,因為您需要點擊日期才能選擇日期。

我可以說你只需要使用另一個日期選擇器。 就像羅傑建議的那樣。

我對接受的答案有一定的困難,並且沒有其他人可以以最小的努力作為基礎。 因此,我決定調整已接受答案的最新版本,直到它至少滿足最低 JS 編碼/可重用性標准。

這是一種比Ben Koehler接受的答案的第三版(最新)更簡潔的解決方案 此外,它將:

  • 不僅適用於mm/yy格式,還適用於任何其他格式,包括 OP 的MM yy
  • 不要在頁面上隱藏其他日期選擇器的日歷。
  • 不要用datestrmonthyear等變量隱式污染全局 JS 對象。

一探究竟:

$('.date-picker').datepicker({
    dateFormat: 'MM yy',
    changeMonth: true,
    changeYear: true,
    showButtonPanel: true,
    onClose: function (dateText, inst) {
        var isDonePressed = inst.dpDiv.find('.ui-datepicker-close').hasClass('ui-state-hover');
        if (!isDonePressed)
            return;

        var month = inst.dpDiv.find('.ui-datepicker-month').find(':selected').val(),
            year = inst.dpDiv.find('.ui-datepicker-year').find(':selected').val();

        $(this).datepicker('setDate', new Date(year, month, 1)).change();
        $('.date-picker').focusout();
    },
    beforeShow: function (input, inst) {
        var $this = $(this),
            // For the simplicity we suppose the dateFormat will be always without the day part, so we
            // manually add it since the $.datepicker.parseDate will throw if the date string doesn't contain the day part
            dateFormat = 'd ' + $this.datepicker('option', 'dateFormat'),
            date;

        try {
            date = $.datepicker.parseDate(dateFormat, '1 ' + $this.val());
        } catch (ex) {
            return;
        }

        $this.datepicker('option', 'defaultDate', date);
        $this.datepicker('setDate', date);

        inst.dpDiv.addClass('datepicker-month-year');
    }
});

您需要的其他一切都是以下 CSS:

.datepicker-month-year .ui-datepicker-calendar {
    display: none;
}

就是這樣。 希望以上內容能為進一步的讀者節省一些時間。

如果有人也想要多個日歷,那么將此功能添加到 jquery ui 並不難。 縮小搜索:

x+='<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix'+t+'">'+(/all|left/.test(t)&&C==0?c?f:n:"")+(

在 x 前面加這個

var accl = ''; if(this._get(a,"justMonth")) {accl = ' ui-datepicker-just_month';}

搜索

<table class="ui-datepicker-calendar

並將其替換為

<table class="ui-datepicker-calendar'+accl+'

還搜索

this._defaults={

將其替換為

this._defaults={justMonth:false,

對於 css,你應該使用:

.ui-datepicker table.ui-datepicker-just_month{
    display: none;
}

完成所有操作后,只需轉到所需的 datepicker init 函數並提供設置 var

$('#txt_month_chart_view').datepicker({
    changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        dateFormat: 'MM yy',
        justMonth: true,
        create: function(input, inst) {
            $(".ui-datepicker table").addClass("badbad");
        },
        onClose: function(dateText, inst) {
            var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
            var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
            $(this).datepicker('setDate', new Date(year, month, 1));
        }
});

justMonth: true是這里的關鍵:)

我有日期選擇器與月份選擇器混合的問題。 我是這樣解決的。

    $('.monthpicker').focus(function()
    {
    $(".ui-datepicker-calendar").show();
    }).datepicker( {
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        dateFormat: 'MM/yy',
        create: function (input, inst) { 

         },
        onClose: function(dateText, inst) { 
            var month = 1+parseInt($("#ui-datepicker-div .ui-datepicker-month :selected").val());           
            var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();

        }
    });

對上述 BrianS 近乎完美的回應進行了一些改進:

  1. 我已經對 show 上設置的值進行了正則表達式,因為我認為在這種情況下它實際上確實使其更具可讀性(盡管請注意我使用的格式略有不同)

  2. 我的客戶不需要日歷,所以我添加了一個顯示/隱藏類添加來做到這一點,而不會影響任何其他日期選擇器。 該類的刪除是在計時器上進行的,以避免表在日期選擇器淡出時閃回,這在 IE 中似乎非常明顯。

編輯:要解決的一個問題是無法清空日期選擇器 - 清除該字段並單擊離開,然后它會重新填充所選日期。

EDIT2:我沒有設法很好地解決這個問題(即沒有在輸入旁邊添加一個單獨的清除按鈕),所以最終只使用了這個: https : //github.com/thebrowser/jquery.ui.monthpicker - 如果有人可以讓標准的 UI 來做這將是驚人的。

    $('.typeof__monthpicker').datepicker({
        dateFormat: 'mm/yy',
        showButtonPanel:true,
        beforeShow: 
            function(input, dpicker)
            {                           
                if(/^(\d\d)\/(\d\d\d\d)$/.exec($(this).val()))
                {
                    var d = new Date(RegExp.$2, parseInt(RegExp.$1, 10) - 1, 1);

                    $(this).datepicker('option', 'defaultDate', d);
                    $(this).datepicker('setDate', d);
                }

                $('#ui-datepicker-div').addClass('month_only');
            },
        onClose: 
            function(dt, dpicker)
            {
                setTimeout(function() { $('#ui-datepicker-div').removeClass('month_only') }, 250);

                var m = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
                var y = $("#ui-datepicker-div .ui-datepicker-year :selected").val();

                $(this).datepicker('setDate', new Date(y, m, 1));
            }
    });

您還需要此樣式規則:

#ui-datepicker-div.month_only .ui-datepicker-calendar {
display:none
}

我喜歡@user1857829 的回答和他的“extend-jquery-like-a-plugin 方法”。 我只是做了一個小小的修改,這樣當你以任何方式更改月份或年份時,選擇器實際上會在字段中寫入日期。 我發現在使用它之后我會喜歡這種行為。

jQuery.fn.monthYearPicker = function(options) {
  options = $.extend({
    dateFormat: "mm/yy",
    changeMonth: true,
    changeYear: true,
    showButtonPanel: true,
    showAnim: "",
    onChangeMonthYear: writeSelectedDate
  }, options);
  function writeSelectedDate(year, month, inst ){
   var thisFormat = jQuery(this).datepicker("option", "dateFormat");
   var d = jQuery.datepicker.formatDate(thisFormat, new Date(year, month-1, 1));
   inst.input.val(d);
  }
  function hideDaysFromCalendar() {
    var thisCalendar = $(this);
    jQuery('.ui-datepicker-calendar').detach();
    // Also fix the click event on the Done button.
    jQuery('.ui-datepicker-close').unbind("click").click(function() {
      var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
      var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
      thisCalendar.datepicker('setDate', new Date(year, month, 1));
      thisCalendar.datepicker("hide");
    });
  }
  jQuery(this).datepicker(options).focus(hideDaysFromCalendar);
}

關於: http : //www.mattkruse.com/javascript/calendarpopup/

選擇月份選擇示例

標記答案工作!! 但不是在我的情況下有不止一個日期選擇器並且只想在特定的日期選擇器上實現

所以我使用 dp 的實例並找到 datepicker Div 並添加隱藏類

這是代碼

<style>
    .hide-day-calender .ui-datepicker-calendar{
        display:none;
    }
</style>

<script>
        $('#dpMonthYear').datepicker({ 
            changeMonth: true,
            changeYear: true,
            showButtonPanel: true,
            dateFormat: 'MM yy',
            onClose: function (dateText, inst) { 
                $(this).datepicker('setDate', new Date(inst.selectedYear, inst.selectedMonth, 1));
            },
            beforeShow: function (elem,dp) {
                $(dp.dpDiv).addClass('hide-day-calender'); //here a change
            }
        });
</script>

注意:您不能定位.ui-datepicker-calendar並設置 css,因為它會在選擇/更改時不斷呈現

我還需要一個月份選擇器。 我做了一個簡單的,標題是年份,下面是 4 個月的 3 行。 檢查一下: 使用 jQuery 的簡單月年選擇器

我嘗試了這里提供的各種解決方案,如果您只是想要幾個下拉菜單,它們就可以正常工作。

此處建議的最佳(外觀等)“選擇器”( https://github.com/thebrowser/jquery.ui.monthpicker )基本上是舊版本的 jquery-ui datepicker 的副本,並重寫了 _generateHTML。 但是,我發現它不再與當前的 jquery-ui (1.10.2) 配合得很好,並且還有其他問題(在 esc 上不關閉,在其他小部件打開時不關閉,具有硬編碼樣式)。

我沒有嘗試修復該月份選擇器,也沒有嘗試使用最新的日期選擇器重新嘗試相同的過程,而是將掛鈎連接到現有日期選擇器的相關部分。

這涉及覆蓋:

  • _generateHTML(構建月份選擇器標記)
  • parseDate (因為它不喜歡沒有日組件時),
  • _selectDay(因為 datepicker 使用 .html() 來獲取日期值)

由於這個問題有點陳舊並且已經得到很好的回答,這里只有 _selectDay 覆蓋來顯示這是如何完成的:

jQuery.datepicker._base_parseDate = jQuery.datepicker._base_parseDate || jQuery.datepicker.parseDate;
jQuery.datepicker.parseDate = function (format, value, settings) {
    if (format != "M y") return jQuery.datepicker._hvnbase_parseDate(format, value, settings);
    // "M y" on parse gives error as doesn't have a day value, so 'hack' it by simply adding a day component
    return jQuery.datepicker._hvnbase_parseDate("d " + format, "1 " + value, settings);
};

如前所述,這是一個老問題,但我發現它很有用,因此想通過替代解決方案添加反饋。

我知道這有點晚了,但幾天前我遇到了同樣的問題,我提出了一個很好且流暢的解決方案。 首先我在這里找到了這個很棒的日期選擇器

然后我剛剛更新了示例附帶的 CSS 類 (jquery.calendarPicker.css),如下所示:

.calMonth {
  /*border-bottom: 1px dashed #666;
  padding-bottom: 5px;
  margin-bottom: 5px;*/
}

.calDay 
{
    display:none;
}

當您更改任何內容時,該插件會觸發一個 DateChanged 事件,因此您沒有單擊某一天並不重要(並且它非常適合作為年份和月份選擇器)

希望能幫助到你!

對於一個月選擇器,使用 JQuery v 1.7.2,我有以下 javascript 就是這樣做的

$l("[id$=txtDtPicker]"). monthpicker ({
showOn: "both",
buttonImage: "../../images/Calendar.png",
buttonImageOnly: true,
pattern: 'yyyymm', // Default is 'mm/yyyy' and separator char is not mandatory
monthNames: ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez']
});

感謝 Ben Koehler 的解決方案。

但是,我遇到了多個日期選擇器實例的問題,其中一些需要選擇日期。 Ben Koehler 的解決方案(在編輯 3 中)有效,但在所有情況下都隱藏了日期選擇。 這是解決此問題的更新:

$('.date-picker').datepicker({
    dateFormat: "mm/yy",
    changeMonth: true,
    changeYear: true,
    showButtonPanel: true,
    onClose: function(dateText, inst) {
        if($('#ui-datepicker-div').html().indexOf('ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all ui-state-hover') > -1) {
            $(this).datepicker(
                'setDate',
                new Date(
                    $("#ui-datepicker-div .ui-datepicker-year :selected").val(),
                    $("#ui-datepicker-div .ui-datepicker-month :selected").val(),
                    1
                )
            ).trigger('change');
            $('.date-picker').focusout();
        }
        $("#ui-datepicker-div").removeClass("month_year_datepicker");
    },
    beforeShow : function(input, inst) {
        if((datestr = $(this).val()).length > 0) {
            year = datestr.substring(datestr.length-4, datestr.length);
            month = datestr.substring(0, 2);
            $(this).datepicker('option', 'defaultDate', new Date(year, month-1, 1));
            $(this).datepicker('setDate', new Date(year, month-1, 1));
            $("#ui-datepicker-div").addClass("month_year_datepicker");
        }
    }
});

這是如何完成的。 截至 2021 年 12 月

$('.monthpicker').datepicker({
    autoclose: true,
    showButtonPanel: true,
    viewMode: "months",
    minViewMode: "months",
    format: "M-yyyy"
})

如果你想保持當前月份被選中然后添加

$('.monthpicker').datepicker({
    autoclose: true,
    showButtonPanel: true,
    viewMode: "months",
    minViewMode: "months",
    format: "M-yyyy"
}).datepicker('setDate', new Date());

使用onSelect回調並手動刪除年份部分並手動設置字段中的文本

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM