简体   繁体   中英

Show wrong month and year when refocused same datepicker input with using jquery ui datepicker

I want to show only month and year. If I refocused same input after select a date, it shows wrong month and year not show previously selected month and year. For example I select December 2010 and then refocused same input it shows April 2015 as below image. How can I?

在此输入图像描述

HTML

<input type="text" class="dp" readonly="true">

CSS

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

JS

$('.dp').datepicker({
    changeMonth: true,
    changeYear: true,
    showButtonPanel: true,
    dateFormat: 'mm.yy',
    onClose: function (dateText, inst) {
        $(this).datepicker('setDate', new Date(inst.selectedYear, inst.selectedMonth, inst.selectedDay));
    }
});

http://jsfiddle.net/46tx62vu/

The datepicker expects to be able to parse the displayed version of the date into a javascript date object.

One way to do this is to add a custom parseDate function for your special date format. The code below looks for the special format of "mm.yy" and if found, parses the value into a date. If the format is anything else, pass processing to the original datepicker.parseDate.

var standardParseDate = $.datepicker.parseDate;

function customParseDate( format, value, options ) {
    if (format === 'mm.yy') {
        var dt = (value + ".").split(".");

        var month = parseInt(dt[0]) - 1;
        var year = parseInt(dt[1]);

        if (year < 100) {
            year += 2000;
        }

        if (isNaN(month) || isNaN(year)) {
            return null;
        }

        return new Date(year, month, 1);
    } else {
        return standardParseDate(format,value,options);
    }
}

$.datepicker.parseDate = customParseDate;

JSFiddle: http://jsfiddle.net/3drfd35t/

additional code for customParseDate:

    } else if (format === 'M-yy') {
      var datestr = value;
      if (datestr.length > 0) {
        var y = datestr.substring(datestr.length - 4, datestr.length);  // last 4 chars
        var m = jQuery.inArray(datestr.substring(0, datestr.length - 5), options.monthNamesShort);
        var newDate = new Date(y, m, 1);
        console.log("customParseDate " + "m:" + m + ", y:" + y); // dbg
        return newDate;
      } else {
        console.log("customParseDate " + "null"); // dbg
        return null;
      }
   } else . . .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM