jQuery UI DatePicker, aby pokazać tylko miesiąc rok

Używam jQuery date picker, aby wyświetlić kalendarz w całej aplikacji. Chcę wiedzieć, czy mogę go użyć do wyświetlenia miesiąca I roku (Maj 2010), a nie kalendarza?

Author: Alexander Abakumov, 2010-02-05

27 answers

Oto hack (zaktualizowany o całość .plik 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>

Edytuj jsfiddle dla powyższego przykładu: http://jsfiddle.net/DBpJe/7755/

Edycja 2 Dodaje wartość miesiąca roku do pola wprowadzania tylko po kliknięciu przycisku Gotowe. Pozwala również na usunięcie wartości pola wejściowego, co nie jest możliwe w powyższym polu http://jsfiddle.net/DBpJe/5103/

Edycja 3 aktualizacja lepszego rozwiązania w oparciu o rozwiązanie rexwolf down.
http://jsfiddle.net/DBpJe/5106

 391
Author: Ben Koehler,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-18 11:37:04

Ten Kod działa mi bez zarzutu:

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

Wyjście To:

Tutaj wpisz opis obrazka

 74
Author: Leniel Maccaferri,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-05 08:06:54

@Ben Koehler, to prefekt! Dokonałem drobnej modyfikacji tak, że używanie pojedynczej instancji selektora daty więcej niż raz działa zgodnie z oczekiwaniami. Bez tej modyfikacji Data jest przetwarzana nieprawidłowo i wybrana wcześniej data nie jest podświetlona.

<!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>
 61
Author: BrianS,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:26:35

Powyższe odpowiedzi są całkiem dobre. Moją jedyną skargą jest to, że nie możesz wyczyścić wartości po jej ustawieniu. Również wolę podejście extend-jquery-like-a-plugin.

To działa idealnie dla mnie:

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

Następnie wywołaj TAK:

$('input.monthYearPicker').monthYearPicker();
 18
Author: user1857829,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-11-28 15:07:38
<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));
            }
        }
    });
});

To rozwiąże problem =) ale chciałem timeFormat yyyy-mm

Tylko próbowałem w FF4 chociaż

 10
Author: Erik Polder,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-05-09 12:53:44

Miałem taką samą potrzebę dzisiaj i znalazłem to na GitHubie, działa z jQueryUI i ma month picker w miejsce dni w kalendarzu

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

 8
Author: Anthony Shaw,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-10-12 04:46:56

Oto, co wymyśliłem. Ukrywa kalendarz bez potrzeby dodatkowego bloku stylu i dodaje przycisk Wyczyść, aby poradzić sobie z problemem braku możliwości wyczyszczenia wartości po kliknięciu na wejściu. Działa również ładnie z wieloma monthpickerami na tej samej stronie.

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('');
    })
);
 8
Author: Paul Richards,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-03-18 20:53:14

Potrzebowałem selektora Miesiąc / Rok dla dwóch pól (Od & Do) I gdy jedno zostało wybrane, Max/Min zostało ustawione na drugim...a la wybierając daty biletów lotniczych. Miałem problemy z ustawieniem max i min...daty drugiego pola zostaną wymazane. Dzięki kilku z powyższych postów...W końcu to rozgryzłem. Musisz ustawić opcje i daty w bardzo konkretnej kolejności.

Zobacz to pełne rozwiązanie: Wybór miesiąca/roku @ JSFiddle

Kod:

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));
            }

        }
    });

Dodaj również to do bloku stylów, jak wspomniano powyżej:

.ui-datepicker-calendar { display: none !important; }
 5
Author: Amy Struck,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-18 16:54:34

Połączyłem wiele z powyższych dobrych odpowiedzi i doszedłem do tego:

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

Okazało się, że działa, ale w obliczu wielu błędów, więc byłem zmuszony do łatania w kilku miejscach datepicker:

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

Patch1: w _showDatepicker: wygładzić skórę;

Patch2: w _checkOffset: aby poprawić pozycjonowanie wybieraka miesiąca (w przeciwnym razie, gdy pole znajduje się na dole przeglądarki, sprawdzanie przesunięcia jest wyłączone);

Patch3: in onClose of _hidedatepicker: otherwise when closing the date pola będą migać przez bardzo krótki okres, co jest bardzo irytujące.

Wiem, że moja poprawka nie była dobra, ale na razie działa. Mam nadzieję, że to pomoże.
 5
Author: rexwolf,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-03 12:27:51

Czy to tylko ja, czy to nie działa tak jak powinno w IE (8)? Data zmienia się po kliknięciu gotowe, ale datepicker otwiera się ponownie, dopóki nie klikniesz gdzieś na stronie, aby stracić fokus na polu wprowadzania...

Szukam rozwiązania tego problemu.
<!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>
 4
Author: Tom Van Schoor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-05-24 12:48:42

Jeśli szukasz miesięcznego selektora spróbuj tego jquery.mtz.monthpicker

To dobrze dla mnie działało.

 4
Author: user2630080,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-12 16:16:26

Waht about: http://www.mattkruse.com/javascript/calendarpopup/

Wybierz miesiąc-wybierz przykład

 3
Author: Roger,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-02-05 16:12:24

Po kopaniu jQueryUI.com dla datepicker, oto mój wniosek i odpowiedź na twoje pytanie.

Po pierwsze, powiedziałbym NIE na twoje pytanie. Nie można używać jQueryUI datepicker do zbierania tylko miesiąc i rok. Nie jest obsługiwana. Nie ma do tego funkcji zwrotnej.

Ale możesz go zhakować do display tylko miesiąc i rok, używając css do ukrycia dni itp. I myślę, że nadal nie ma sensu, bo musisz kliknąć daty, aby wybrać randka.

Mogę powiedzieć, że musisz użyć innego datepickera. Tak jak zasugerował Roger.

 3
Author: Reigel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-02-05 16:59:27

Miałem problem z date picker zmieszany z month picker. Tak to rozwiązałem.

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

        }
    });
 3
Author: PYT,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-06-24 09:31:51

Jeśli ktoś chce, że również dla wielu kalendarzy nie jest bardzo trudne, aby dodać tę funkcjonalność do jQuery ui. z minifikowanym szukaniem:

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

Dodaj to przed x

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

Szukaj

<table class="ui-datepicker-calendar

I zastąp go

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

Szukaj też

this._defaults={

Zastąp go

this._defaults={justMonth:false,

Do css powinieneś użyć:

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

Po tym wszystkim Wystarczy przejść do żądanych funkcji datepicker init i podać ustawienie 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 jest tu klucz:)

 3
Author: prdatur,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-01-17 18:41:58

Zrobiłem kilka udoskonaleń do niemal idealnej odpowiedzi Briana powyżej:

  1. I ' ve regexed wartość ustawiona na pokaz, ponieważ myślę, że faktycznie sprawia, że nieco bardziej czytelne w tym przypadku (chociaż Uwaga używam nieco inny format)

  2. Mój klient nie chciał kalendarza, więc dodałem dodatek do klasy on show / hide, aby zrobić to bez wpływu na inne datepickers. Usunięcie klasy jest na czas, aby uniknąć tabeli migające z powrotem w górę jako datepicker zanika, co wydaje się być bardzo zauważalne w IE.

EDIT: problem, który pozostał do rozwiązania, polega na tym, że nie ma możliwości opróżnienia datepicker - wyczyść pole i kliknij Dalej, a zostanie ono ponownie wypełnione z wybraną datą.

EDIT2: nie udało mi się tego ładnie rozwiązać (tzn. bez dodawania osobnego przycisku Clear obok wejścia), więc skończyło się na tym: https://github.com/thebrowser/jquery.ui.monthpicker - Jeśli ktoś może dostać standardowy interfejs użytkownika, aby to zrobić, byłoby niesamowite.

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

Potrzebna jest również reguła stylu:

#ui-datepicker-div.month_only .ui-datepicker-calendar {
display:none
}
 3
Author: Whelkaholism,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-11-13 15:56:04

Podobnie jak wiele innych, napotkałem wiele problemów próbując to zrobić, i tylko kombinacja opublikowanych rozwiązań, a w końcu Wielki hack, aby to idealne rozwiązanie, wylądował mi rozwiązanie.

Problemy z innymi rozwiązaniami w tym wątku, które próbowałem:

  1. wybranie nowej daty w datepickerze zmieni również (wewnętrzną) datę innych datepickerów, więc po ponownym otwarciu innych (lub próbie uzyskania ich daty), będą mieli inną datę Data niż ta wyświetlana w przypisanym im polu wejściowym.
  2. datepicker nie będzie "pamiętał" daty ponownego otwarcia.
  3. kod do żonglowania datami używanymi podciągami, więc nie był kompatybilny ze wszystkimi formatami.
  4. "my monthpicker" zmienił tylko pole wejściowe przy zamykaniu, a nie za każdym razem, gdy wartości zostały zmienione.
  5. pole wejściowe nie jest poprawnie aktualizowane, jeśli wpiszesz błędnie sformatowany ciąg wejściowy dla daty, a następnie klikniesz "Zamknij" na datepicker.
  6. nie mogę mieć normalnych datepickerów, które pokazują dni, na tej samej stronie co monthpickers, które nie pokazują dni.

W końcu znalazłem sposób, aby naprawić wszystkie te problemy . Pierwsze cztery można naprawić po prostu uważając, jak odwołujesz się do daty i monthpickerów w ich wewnętrznym kodzie, i oczywiście wykonując ręczną aktualizację pickerów. Można to zobaczyć w instancjacji-przykłady na dole. Piąty problem może możesz pomóc, dodając niestandardowy kod do funkcji datepicker.

UWAGA: nie musisz używać następujących skryptów monthpicker, aby naprawić trzy pierwsze problemy w normalnym datepicker. Wystarczy użyć datepicker instantiation-script u dołu tego postu.

Teraz, aby użyć monthpickers i naprawić ostatni problem, musimy oddzielić datepickers i monthpickers. Możemy dostać jeden z niewielu jQuery-UI monthpicker addons tam, ale niektórych brakuje elastyczność/umiejętność lokalizacji, niektórym brakuje animacji support...so, co robić? Roll your " own " from the datepicker-code! to daje Ci w pełni funkcjonalny monthpicker, ze wszystkimi funkcjami datepicker, tylko bez wyświetlania dni.

Dostarczyłem monthpicker js-script oraz towarzyszący CSS-script, używając metody opisanej poniżej, z kodem jQuery-UI v1.11.1. Wystarczy skopiować te fragmenty kodu do dwóch nowe pliki, monthpicker.js i monthpicker.css, odpowiednio.


Oto proces, przez który przeszedłem, aby sklonować oryginalny datepicker i uczynić go monthpicker

Jeśli nie obchodzi cię, jak je zrobiłem, przewiń obok tej sekcji ,i w dół do linii " Teraz dodać datepickers i monthpickers na stronie!"

Wziąłem cały kod javascript z jquery-ui-1.11.1.js, wklejając go do nowego pliku js i wymieniając następujące ciągi:

  • "datepicker" = = > "monthpicker"
  • "Datepicker" = = > "Monthpicker"
  • "Date picker" = = > "month picker"
  • "Date picker" = = > "Month picker"

Następnie usunąłem część for-loop, która tworzy cały ui-datepicker-calendar div (inne rozwiązania ukrywają się za pomocą CSS). Można to znaleźć w funkcji _generatehtml: (inst).

Znajdź linię, która mówi:

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

Zaznacz wszystko od po zamykający znacznik div i w dół do (i nie włącznie) linii, w której jest napisane:

drawMonth++;
Teraz to będzie nieszczęśliwe, bo musimy zamknąć pewne sprawy. Po zakończeniu tego znacznika div, dodaj to:
";

Kod powinien być teraz ładnie zszyty. Oto fragment kodu pokazujący, z czym powinieneś skończyć:

...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...

Następnie skopiowałem / wkleiłem kod z jquery-ui.css odnoszący się do datepickerów do nowego pliku CSS i zastąpił następujące ciągi:

  • "datepicker" = = > "monthpicker"

Teraz dodać datepickers i monthpickers na stronie!

Te następujące fragmenty kodu javascript działają z wieloma datepickerami i / lub monthpickerami na stronie, bez wyżej wymienionych problemów! Fixed General by using ' $(this). dużo :)

Pierwszy skrypt jest dla zwykłego datepickera, a drugi dla" nowego " monthpickera.

Out-commented .po , który pozwala utworzyć element, aby wyczyścić pole wejściowe, jest wykradziony z odpowiedzi Paula Richardsa.

Używam formatu "MM yy" w moim monthpicker, i "yy-MM-dd" w moim datepicker, ale to jest całkowicie kompatybilny ze wszystkimi formatami , więc możesz używać dowolnego z nich, który chcesz. Po prostu zmień opcję "dateFormat". Standardowe opcje "showButtonPanel", "showAnim" i "yearRange" są oczywiście opcjonalne i konfigurowalne do twojego życzenia.


Dodawanie datepickera

Datepicker instantiation. Ten ciągnie się od 90 lat temu do dnia dzisiejszego. Pomaga utrzymać poprawne pole wejściowe, szczególnie jeśli ustawisz opcje defaultDate, minDate i maxDate, ale poradzi sobie z tym, jeśli tego nie zrobisz. będzie działać z dowolnym formatem dateFormat, który wybierzesz.

        $('#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('');
    //    })
    //)
    ;

Dodawanie monthpickera

Dołącz monthpicker.plik js i monthpicker.plik css na stronie, której chcesz użyć monthpickers.

Monthpicker instantiation Wartość pobierana z tego miesięcypicker, jest zawsze pierwszym dniem wybranego miesiąca. Rozpoczyna się w bieżącym miesiącu i waha się od 100 lat temu i 10 lat w przyszłości.

    $('#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('');
    //    })
    //)
    ;

To jest to! To wszystko, czego potrzebujesz, aby zrobić monthpicker.

Nie wydaje mi się, aby jsfiddle działał z tym, ale działa dla mnie w moim ASP.NET projekt MVC. Po prostu zrób to, co zwykle, aby dodać datepicker do swojej strony, i włącz powyższe Skrypty, ewentualnie zmieniając selektor (czyli $("#MyMonthTextBox")) na coś, co działa dla Ciebie.

Mam nadzieję, że to komuś pomoże. W 2007 roku został wybrany do Izby Gmin jako reprezentant kraju.]}
  1. Monthpicker pracuje ostatniego dnia miesiąca . Data, którą otrzymasz od tego miesięcypicker zawsze będzie ostatnim dniem miesiąca.

  2. Dwa miesiące temu ; 'start' jest pracujemy nad pierwszym z miesiąca, a 'koniec' pracuje nad ostatnim z miesiąca. Oba są ograniczone przez siebie, więc wybór miesiąca na "koniec", który jest przed wybranym miesiącem na "początek", zmieni "początek" na ten sam miesiąc co "koniec". I vice versa. Opcjonalnie: po wybraniu miesiąca na "start", "minDate" jest ustawiony na "koniec". Aby usunąć tę funkcję, skomentuj jedną linię w onClose (przeczytaj komentarze).

  3. Dwa współpracujące datepickers ; oba są ograniczone przez siebie, więc wybór daty na "koniec", która jest przed wybraną datą na "początek", zmieni "początek" na ten sam miesiąc co "koniec". I vice versa. Opcjonalnie: po wybraniu daty na 'start', 'minDate' jest ustawiony na 'end'. Aby usunąć tę funkcję, skomentuj jedną linię w onClose (przeczytaj komentarze).

 3
Author: Ultroman the Tacoman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-15 08:09:31

Dodaj jeszcze jedno proste rozwiązanie

 $(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/
Funkcje:

  • Wyświetl tylko miesiąc / rok
  • dodaje wartość roku miesiąca do pola wprowadzania tylko po kliknięciu przycisku Gotowe
  • brak zachowania "reopen" po kliknięciu " Done"
    ------------------------------------
    inne rozwiązanie, które działa dobrze dla datepicker i monthpicker na tej samej stronie: (również uniknąć błędu mutiple kliknij na Poprzedni Przycisk w IE, które mogą wystąpić, jeśli użyjemy funkcji focus)
    js fiddle link
 3
Author: Chinh Phan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-25 10:53:10

Podobała mi się odpowiedź @user1857829 i jego podejście "extend-jQuery-like-a-plugin". Właśnie dokonałem modyfikacji litte tak, że gdy zmienisz miesiąc lub rok w jakikolwiek sposób picker faktycznie pisze datę w polu. Stwierdziłem, że chciałbym takie zachowanie po użyciu go trochę.

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);
}
 2
Author: stravanato,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-03-05 11:30:56

Miałem pewne trudności z zaakceptowaną odpowiedzią i nikt inny nie mógł być użyty przy minimalnym wysiłku jako podstawa. Postanowiłem więc dostosować najnowszą wersję zaakceptowanej odpowiedzi, dopóki nie spełni co najmniej minimalnych standardów kodowania JS / wielokrotnego użytku.

Oto sposóbznacznie czystsze rozwiązanie niżtrzecie (ostatnie) wydanie Ben Koehler 's zaakceptowanej odpowiedzi. Ponadto:

  • pracować nie tylko z formatem mm/yy, ale z dowolnym inne, w tym OP ' s MM yy.
  • nie Ukryj kalendarza innych datepickerów na stronie.
  • nie zanieczyszczają pośrednio globalnego obiektu JS datestr, month, year zmienne etc.

Zobacz:

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

I wszystko inne, czego potrzebujesz, to następujący CSS gdzieś wokół:

.datepicker-month-year .ui-datepicker-calendar {
    display: none;
}
To wszystko. Mam nadzieję, że powyższe zaoszczędzi trochę czasu dla dalszych czytelników.
 2
Author: Alexander Abakumov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:10:42

Wiem, że to trochę późna odpowiedź, ale mam ten sam problem kilka dni wcześniej i przyszedłem z ładnym i gładkim rozwiązaniem. Najpierw znalazłem ten świetny wybór daty tutaj

Wtedy właśnie zaktualizowałem klasę CSS (jquery.calendarPicker.css), który znajduje się w przykładzie takim jak:

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

.calDay 
{
    display:none;
}

Wtyczka uruchamia event DateChanged po zmianie czegokolwiek, więc nie ma znaczenia, że nie klikasz na dzień (i pasuje ładnie jako rok i miesiąc picker)

Mam nadzieję, że to pomoże!
 1
Author: pjnovas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-12-27 23:26:38

Potrzebowałem też miesięcznego zbieracza. Zrobiłem prosty z nagłówkiem roku i 3 rzędami 4 miesięcy poniżej. Sprawdź: prosty selektor miesięczny z jQuery .

 1
Author: Tiago Coelho,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-10-20 03:11:38

Próbowałem różnych rozwiązań dostarczonych tutaj i działały dobrze, jeśli po prostu chcesz kilka upadków.

The best (in appearance etc) 'picker' ( https://github.com/thebrowser/jquery.ui.monthpicker ) sugerowany tutaj jest w zasadzie kopią starej wersji jQuery-UI datepicker z przepisanym _generatehtml. Jednak okazało się, że nie gra już ładnie z bieżącym jQuery-ui (1.10.2) i miał inne problemy (nie zamyka się na esc, nie zamyka się na innym widżecie otwieranie, ma zakodowane na twardo style).

Zamiast próbować naprawić monthpicker i zamiast ponownie przypisać ten sam proces z najnowszym datepicker, poszedłem z podłączeniem do odpowiednich części istniejącego selektora dat.

Polega to na nadpisaniu:

  • _generateHTML (aby zbudować znacznik wyboru miesiąca)
  • parseDate (jak nie lubi gdy nie ma komponentu dnia),
  • _selectDay (jak używa datepicker .html () to get the day wartość)

Ponieważ to pytanie jest trochę stare i już dobrze odpowiedział, Oto tylko obejście _selectday, aby pokazać, jak to zostało zrobione:

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);
};

Jak stwierdzono, jest to stare pytanie, ale uznałem to za przydatne, więc chciałem dodać opinię z alternatywnym rozwiązaniem.

 1
Author: freedomn-m,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-03-21 12:02:41

Przez miesiąc, używając JQuery v 1.7.2, mam następujący javascript, który robi właśnie to

$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']
});

 0
Author: Ricardo Appleton,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-07 16:14:20

Wszyscy tutaj dostają wartość miesiąca , roku jak ta,

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

Ale teraz mam problem podczas pobierania wartości z > i <. Ponieważ daje nam wartość wybranej wartości z listy rozwijanej, więc dostarcza nam wartość old, a nie wartości new.

Więc, zgodnie z dokumentem jQuery UI : - http://api.jqueryui.com/datepicker/. Możemy bezpośrednio pobrać Rok , Miesiąc z funkcji. Dla innych wartości jak day itd. możemy łatwo uzyskać do nich dostęp poprzez inst jqueryUI funkcja. Możemy uzyskać dostęp do inst jak poniżej,

 var day = inst.selectedDay;

Tak więc, używając onChangeMonthYear możemy uzyskać bieżące wartości miesiąca, roku i dnia bezpośrednio z funkcji, więc nie trzeba pracować dla wybranej wartości.

HTML: -

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

Script: -

$( function() {
    $(".monthPicker").datepicker({
        dateFormat: 'MM yy',
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        beforeShow: true,
        onChangeMonthYear: function(year , month , inst) {

            setTimeout(function() {
               $('.ui-datepicker-calendar').hide();
            });
            var day = inst.selectedDay;
            month = month;
            year = year;
            var current_date =  year + "-" + month + "-" + day ;                
        }
    });
    $(".monthPicker").focus(function () {
        $(".ui-datepicker-calendar").hide();
        $("#ui-datepicker-div").position({
            my: "center top",
            at: "center bottom",
            of: $(this)
        });
    });
});

Uwaga: - to może być przydatne, gdy chcemy inline monthpicker. Wystarczy zamienić pole wejściowe na division i możemy go używać inline podczas używania inline upewnij się, że używasz onChangeMonthYear,

Dla Inline MonthPicker :-

<div class="monthpicker">  </div>
 0
Author: Bhavin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-08 07:52:57

Dzięki za rozwiązanie Bena Koehlera.

Jednak miałem problem z wieloma instancjami datepickerów, niektóre z nich były potrzebne przy doborze dnia. Rozwiązanie Bena Koehlera (w edycji 3) działa, ale ukrywa wybór dnia we wszystkich przypadkach. Oto aktualizacja, która rozwiązuje ten problem :

$('.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");
        }
    }
});
 0
Author: dj3c1t,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-04 09:36:41

Use onSelect call back and remove the year portion manually and set the text in the field manually

 -2
Author: Teja Kantamneni,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-02-05 16:14:03