388

jQuery 日付ピッカーを使用して、アプリ全体にカレンダーを表示しています。カレンダーではなく、月と年 (2010 年 5 月) を表示するために使用できるかどうかを知りたいですか?

4

28 に答える 28

444

これがハックです(.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/

編集 3 は、rexwolf のソリューション ダウンに基づいて、Better Solution を更新しました。
http://jsfiddle.net/DBpJe/5106

于 2010-02-05T17:36:05.830 に答える
95

このコードは私にとって完璧に機能しています:

<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" />

出力は次のとおりです。

ここに画像の説明を入力

于 2011-05-16T04:11:28.640 に答える
66

@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>
于 2010-08-26T17:17:44.660 に答える
18

上記の答えはかなり良いです。私の唯一の不満は、一度設定すると値をクリアできないことです。また、extend-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();
于 2012-11-28T14:51:37.620 に答える
10
<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でしか試してないけど

于 2011-05-09T12:53:44.873 に答える
9

私は今日これと同じニーズを持っていて、これをgithubで見つけ、jQueryUIで動作し、カレンダーの日の代わりに月ピッカーを持っています

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

于 2012-10-12T04:46:56.653 に答える
8

これが私が思いついたものです。余分なスタイルブロックを必要とせずにカレンダーを非表示にし、入力をクリックすると値をクリアできないという問題に対処するためのクリアボタンを追加します。また、同じページの複数の月ピッカーでもうまく機能します。

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('');
    })
);
于 2013-03-15T05:34:55.520 に答える
7

他の多くの人と同じように、私はこれを行おうとして多くの問題に遭遇しました。投稿されたソリューションの組み合わせ、そして最終的にそれを完璧にするための大きなハックだけが、すべての日付形式とローカリゼーションで動作するソリューションにたどり着きました。通常の日付ピッカー。

私が試したこのスレッドの他の解決策の問題:

  1. 日付ピッカーで新しい日付を選択すると、他の日付ピッカーの (内部) 日付も変更されるため、他の日付ピッカーを再度開くと (または日付を取得しようとすると)、割り当てられた入力に表示されている日付とは異なる日付になります。 -分野。
  2. 日付ピッカーは、再度開いたときに日付を「記憶」しません。
  3. 日付をジャグリングするコードは部分文字列を使用していたため、すべての形式と互換性がありませんでした。
  4. 間違った形式の日付の入力文字列を入力し、日付ピッカーで [閉じる] をクリックすると、入力フィールドが正しく更新されませんでした。
  5. monthpicker は、値が変更されるたびにではなく、入力フィールドを閉じるときにのみ変更しました。
  6. 日を表示しない月ピッカーと同じページに、日を表示する通常の日付ピッカーを配置することはできません。

元の日付ピッカーであっても、これらの問題をすべて修正する方法をついに見つけました。

注:通常のjQuery datepickersの最初の 4 つの問題を修正するために、次のmonthpicker スクリプトを使用する必要はありません。この投稿のさらに下にあるDatepicker インスタンス化スクリプトを使用するだけです。問題 5 と 6 は、私が試したさまざまな monthpicker ソリューションにのみ関連しています。

問題 1 ~ 3 および 5 は、日付ピッカーと月ピッカーが内部コードでどのように参照されるかに関係しており、他の日付ピッカーと月ピッカーに干渉しないようにし、ピッカーを手動で更新する必要がありました。これは、以下のインスタンス化の例で確認できます。4 番目の問題は、カスタム コードを datepicker 関数に追加することで修正されました (例のコメント、特に onClose に関するコメントを参照してください)。

datepickers と一緒に monthpickersを使用することにのみ関係する 6 番目と最後の問題については、 datepickers と monthpickersを適切に分離する必要があります。

では、数少ないカスタム jQuery-UI monthpicker アドオンの 1 つを入手してみませんか? これを書いたときに見つけたものは、ローカリゼーションの柔軟性/能力に欠けていて、いくつかはアニメーションのサポートに欠けていました...だから、どうすればいいですか? datepicker-code から「独自の」ロールを作成してください。これにより、日付ピッカーのすべての機能を備えた完全に機能する月ピッカーが得られますが、日付は表示されません。

以下で説明する方法を使用して、jQuery-UI v1.11.1 コードを使用して、monthpicker js-scriptとそれに付随する CSS-scriptを提供しました。これらのコード スニペットを、それぞれ monthpicker.js と monthpicker.css という 2 つの新しいファイルにコピーするだけです。

datepicker を monthpicker に変換するかなり単純なプロセスについて読みたい場合は、最後のセクションまでスクロールしてください。その後、新しいバージョンの jQuery-UI でこのプロセスを繰り返すことができます。


ページに日付ピッカーと月ピッカーを追加します。

これらの次の JavaScript コード スニペットは、前述の問題なしで、ページ上の複数の日付ピッカーおよび/または月ピッカーで動作します! 「$(this)」を使用することで一般的に修正されます。多くの :)

最初のスクリプトは通常の日付ピッカー用で、2 番目のスクリプトは「新しい」月ピッカー用です。

入力フィールドをクリアするための要素を作成できるアウトコメントされた.afterは、Paul Richards の回答から盗まれています。

月ピッカーでは「MM yy」形式を使用し、日付ピッカーでは「yy-mm-dd」形式を使用していますが、これはすべての形式と完全に互換性があるため、どちらを使用してもかまいません。「dateFormat」オプションを変更するだけです。標準オプションの 'showButtonPanel'、'showAnim'、および 'yearRange' はもちろんオプションであり、必要に応じてカスタマイズできます。


日付ピッカーの追加

デートピッカーのインスタンス化。 これは90年前から現在まで続いています。特に defaultDate、minDate、および maxDate オプションを設定している場合は、入力フィールドを正しく保つのに役立ちますが、そうでない場合は処理できます。選択した任意の dateFormat で機能します。

注:多くの "new Date()" 呼び出しはばかげているように見えますが、(私の知る限り) 再利用可能なインスタンスを作成できないため、動的な Date を宣言にパックする別の方法を見つけることができません。その文脈で。minDate と maxDate を設定するようなコンテキストで拡張された Date を設定するより良い方法を誰かが知っている場合は、大いに感謝します!

        $('#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 を使用するページに monthpicker.js ファイルと monthpicker.css ファイルを含めます。

Monthpicker のインスタンス化 この 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('');
    //    })
    //)
    ;

それでおしまい! これで、monthpicker を作成するために必要なすべてのことができます。

これでjsfiddleを機能させることはできないようですが、ASP.NET MVCプロジェクトでは機能しています。日付ピッカーをページに追加するために通常行っていることを実行し、上記のスクリプトを組み込みます。おそらく、セレクター ($("#MyMonthTextBox") を意味する) を自分に合ったものに変更します。

これが誰かに役立つことを願っています。

いくつかの追加の日付ピッカーと月ピッカーのセットアップ用のペーストビンへのリンク:

  1. 月の最終日に動作する Monthpicker。この monthpicker から取得する日付は、常にその月の最終日になります。

  2. 2 つの協力的な monthpicker ; 'start' は月の最初に、'end' は月の最後に働きます。どちらも互いに制限されているため、「開始」で選択した月よりも前の「終了」の月を選択すると、「開始」が「終了」と同じ月に変更されます。およびその逆。オプション: 「start」で月を選択すると、「end」の「minDate」がその月に設定されます。この機能を削除するには、onClose の 1 行をコメント アウトします (コメントを読んでください)。

  3. 2 つの協力する datepicker ; どちらも互いに制限されているため、「開始」で選択した日付より前の「終了」の日付を選択すると、「開始」が「終了」と同じ月に変更されます。およびその逆。オプション: 「開始」の日付を選択すると、「終了」の「minDate」がその日付に設定されます。この機能を削除するには、onClose の 1 行をコメント アウトします (コメントを読んでください)。


DatePicker を MonthPicker に変更する方法

日付ピッカーに関連する jquery-ui-1.11.1.js からすべての JavaScript コードを取得し、新しい js ファイルに貼り付けて、次の文字列を置き換えました。

  • 「日付ピッカー」 ==> 「月ピッカー」
  • 「日付ピッカー」 ==> 「月ピッカー」
  • 「日付ピッカー」 ==> 「月ピッカー」
  • 「日付ピッカー」 ==> 「月ピッカー」

次に、ui-datepicker-calendar div (他のソリューションが CSS を使用して非表示にする div) 全体を作成する for ループの部分を削除しました。これは _generateHTML: 関数 (inst) にあります。

次の行を見つけます。

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

終了 div タグの後から次の行まで (および含めないで)すべてをマークします。

drawMonth++;

いくつかのものを閉じる必要があるため、今は不幸になります。前の div タグを閉じた後、これを追加します。

";

コードはうまくつなぎ合わされているはずです。最終的に何をすべきかを示すコードスニペットを次に示します。

...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 ファイルにコードをコピーして貼り付け、次の文字列を置き換えました。

  • 「日付ピッカー」 ==> 「月ピッカー」
于 2014-09-24T07:46:42.873 に答える
5

2 つのフィールド (開始日と終了日) の月/年ピッカーが必要で、1 つが選択されると、最大/最小がもう 1 つのフィールドに設定されました...航空券の日付を選択するように。最大値と最小値の設定に問題がありました...他のフィールドの日付が消去されます。上記の投稿のいくつかのおかげで...私はついにそれを理解しました。オプションと日付を特定の順序で設定する必要があります。

完全なソリューションについては、このフィドルを参照してください: 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; }
于 2012-12-18T16:54:34.217 に答える
5

上記の良い答えの多くを組み合わせて、これに到達しました:

    $('#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: in _showDatepicker : 非表示を滑らかにする;

patch2: in _checkOffset: 月ピッカーの位置を修正します (それ以外の場合、フィールドがブラウザーの下部にある場合、オフセット チェックはオフになります)。

パッチ 3: _hideDatepicker の onClose: そうしないと、日付フィールドを閉じるときに非常に短い時間点滅し、非常に煩わしくなります。

私の修正がうまくいかなかったことはわかっていますが、今のところは機能しています。それが役に立てば幸い。

于 2013-09-12T09:43:27.820 に答える
4

受け入れられた回答には特定の問題があり、最小限の労力でベースとして使用できるものは他にありません。そのため、少なくとも最低限のJSコーディング/再利用基準を満たすまで、受け入れられた回答の最新バージョンを微調整することにしました。

これは、Ben Koehlerの受け入れられた回答の第 3 (最新) 版よりもはるかにクリーンなソリューションです。さらに、次のようになります。

  • 形式だけでなくmm/yy、OP を含む他の形式でも機能しますMM yy
  • ページ上の他の日付ピッカーのカレンダーを非表示にしないでください。
  • datestr、 などの変数monthでグローバル JS オブジェクトを暗黙的に汚染しないでください。year

見てみな:

$('.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;
}

それでおしまい。上記がさらなる読者のために時間を節約することを願っています.

于 2015-11-30T00:13:54.550 に答える
4

If you are looking for a month picker try this jquery.mtz.monthpicker

This worked for me well.

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);
于 2013-07-29T11:23:01.780 に答える
4

それは私だけですか、それとも 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>
于 2011-05-24T12:48:42.287 に答える
3

複数のカレンダーに対してもそれが必要な場合は、この機能を 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関数に移動し、設定変数を提供します

$('#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ここでの鍵です:)

于 2011-05-09T20:10:44.923 に答える
3

datepicker のために jQueryUI.com を掘り下げた後、ここに私の結論とあなたの質問への回答があります。

まず、あなたの質問にはノーと言います。月と年のみを選択するために jQueryUI datepicker を使用することはできません。サポートされていません。そのためのコールバック関数はありません。

ただし、css を使用して日を非表示にするなどして、月と年のみを表示するようにハックすることもできます。また、日付を選択するために日付をクリックする必要があるため、意味がないと思います。

別の日付ピッカーを使用する必要があると言えます。ロジャーが提案したように。

于 2010-02-05T16:59:27.337 に答える
3

日付ピッカーと月ピッカーが混在するという問題がありました。そのように解決しました。

    $('.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();

        }
    });
于 2011-05-14T14:02:27.053 に答える
2

について: http://www.mattkruse.com/javascript/calendarpopup/

月選択の例を選択

于 2010-02-05T16:12:24.050 に答える
2

@ 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);
}
于 2013-03-05T11:30:56.570 に答える
2

上記の BrianS のほぼ完璧な応答にいくつかの改良を加えました。

  1. この場合、実際には少し読みやすくなると思うので、ショーに設定された値を正規表現しました(ただし、わずかに異なる形式を使用していることに注意してください)

  2. 私のクライアントはカレンダーを望んでいなかったので、他の日付ピッカーに影響を与えずにそれを行うために on show / hide クラスを追加しました。クラスの削除は、日付ピッカーがフェードアウトするときにテーブルがフラッシュバックするのを避けるためにタイマーで行われます。これは、IE では非常に目立つようです。

編集:これで解決すべき問題の1つは、日付ピッカーを空にする方法がないことです-フィールドをクリアしてクリックすると、選択した日付が再入力されます.

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
}
于 2012-11-13T14:52:08.430 に答える
1

ここで提供されているさまざまなソリューションを試しましたが、いくつかのドロップダウンが必要な場合は問題なく機能しました。

ここで提案されている最高の(外観など)'picker'(https://github.com/thebrowser/jquery.ui.monthpicker)は、基本的に、_generateHTMLが書き直された古いバージョンのjquery-uidatepickerのコピーです。ただし、現在の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);
};

述べたように、これは古い質問ですが、私はそれが有用であることがわかったので、代替ソリューションでフィードバックを追加したいと思いました。

于 2013-03-21T12:02:41.083 に答える
1

返信が少し遅れていることは承知していますが、数日前に同じ問題が発生し、素晴らしくスムーズな解決策が得られました. 最初に、この素​​晴らしい日付ピッカーをここで見つけました

次に、この例に付属する CSS クラス (jquery.calendarPicker.css) を次のように更新しました。

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

.calDay 
{
    display:none;
}

何かを変更すると、プラグインはイベント DateChanged を発生させるため、日付をクリックしていなくても問題ありません (年と月のピッカーとしても適しています)。

それが役に立てば幸い!

于 2010-12-27T23:26:38.767 に答える
1

月ピッカーも必要でした。ヘッダーに年、その下に 4 か月の 3 行のシンプルなものを作成しました。確認してください: jQuery を使用したシンプルな月年ピッカー

于 2012-05-31T11:56:02.433 に答える
-2

コールバックを使用onSelectして手動で年の部分を削除し、フィールドにテキストを手動で設定します

于 2010-02-05T16:14:03.813 に答える