10

I have a datepicker that's on an input field, default date when I first open it is today's date, which is what I want.
However, when I select a date and I clear the input field, the datepicker still has the selected date on it, which I don't want

Does anyone have an idea why this happens and how I can prevent this behavior?

Avnesh Shakya
  • 3,828
  • 2
  • 23
  • 31
J.Pip
  • 4,523
  • 7
  • 31
  • 49

5 Answers5

37

The proper way to reset the date of a Datepicker widget is like this:

$.datepicker._clearDate('#input_field_goes_here');

Or like this:

$('#input_field_goes_here').datepicker('setDate', null);

Whichever works best for you.

silkfire
  • 24,585
  • 15
  • 82
  • 105
12

See http://codepen.io/alexgill/pen/yOQrwV

$(SELECTOR).datepicker('setDate', null);
Alex Gill
  • 2,395
  • 1
  • 16
  • 18
7

Clear button in calendar.

 $("#txtCalendar").datepicker({
        showButtonPanel: true,
        closeText: 'Clear',
        onClose: function (dateText, obj) {
            if ($(window.event.srcElement).hasClass('ui-datepicker-close'))
                $("#txtCalendar").val('');
        }
    });
Shahbaz Ahmad
  • 161
  • 1
  • 9
  • 4
    great but changed $("#txtCalendar").val(''); to $(this).val(''); for multiple instances – Barry Dowd Jan 18 '17 at 07:01
  • @BarryDowd This looks clever. However I get `window.event is undefined` (at least in Firefox). Any workaround? Thanks! – SeaBass Aug 21 '18 at 18:15
  • @SeaBass the example is using a deprecated reference (`window.event.srcElement`), in order to make it work, you need to replace it with `event.target`. Reference: https://developer.mozilla.org/en-US/docs/Web/API/Event/srcElement – funder7 Sep 20 '21 at 21:17
1

Just add this code

}).keyup(function(e) {
    if(e.keyCode == 8 || e.keyCode == 46) {
        $.datepicker._clearDate(this);
    }
});

You can use backspace to clear field even if it has in read only mode. Source

PIYUSH Itspk
  • 13
  • 1
  • 9
0

To really reset everything, including the selected year in the date selector popup, I had to do the following:

$(SELECTOR).datepicker('setDate', new Date());
$(SELECTOR).datepicker('setDate', null);

Just doing the last line results in the previously selected year to show in the date selector