97

How do I reset the datepicker calendar values?.. The min and max date restrictions?

The problem is that when I clear the dates (by deleting the textbox values), the previous date restrictions are still applied.

I've been sorting through the documentation and nothing jumped out as a solution. I also wasn't able to find a quick fix on a SO/google search

http://jsfiddle.net/CoryDanielson/tF5MH/


Solution:

// from & to input textboxes with datepicker enabled
var dates = $("input[id$='dpFrom'], input[id$='dpTo']");

// #clearDates is a button to clear the datepickers
$('#clearDates').on('click', function(){
    dates.attr('value', '');
    dates.each(function(){
        $.datepicker._clearDate(this);
    });
});​​

_.clearDate() is a private method of the DatePicker object. You won't find it in the public API on jQuery UI's website, but it works like a charm.

Cory Danielson
  • 14,314
  • 3
  • 44
  • 51

17 Answers17

93

I was trying to accomplish this very thing, that is, empty the datepicker so that filters entered by the user could be removed. Googling a bit I found this sweet piece of code:

You can add the clear feature even on read only fields. Just add the following code to your datepicker:

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

People will be able to highlight (even Read Only fields) and then use backspace or delete key to remove the date using _clearDate function.

Source

Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480
  • 10
    Wow. Why wouldn't that be publicized?! It's excluded from the API on jQuery UI as well.... makes no sense. ---- I edited your post so that the solution matches my question better. Very nice find – Cory Danielson Oct 01 '12 at 08:23
  • Isn't your edit already active? I can't see an option to accept your edit... :) – Leniel Maccaferri Oct 01 '12 at 18:37
  • nope, I still see your old post with the `keyup` function... not too sure how edits work, i guess – Cory Danielson Oct 01 '12 at 19:17
  • Your edit was rejected by someone else: http://stackoverflow.com/review-beta/suggested-edits/735073 Don't know if you'll be able to access the link. – Leniel Maccaferri Oct 01 '12 at 19:20
  • I've edited the original post to include the new solution. Thanks a lot for the find. I'm stunned that it wasn't publicized in the API. It is literally the EXACT function I was looking for and expected to find. – Cory Danielson Oct 01 '12 at 21:11
  • Nice idea... What I can do is to copy your reviewed code that was reject by the reviewer and paste it my answer. What do you think? – Leniel Maccaferri Oct 01 '12 at 21:14
  • 3
    Nah, that's okay. I think that both the solution included in my original post and yours will help almost anybody who finds their way to this page. Maybe some comments about what keyCode 8 and 46 are or what `this` is exactly inside of _clearDates() – Cory Danielson Oct 01 '12 at 21:15
  • 3
    where exactly do you put this? – w0051977 Sep 14 '17 at 16:49
  • I had to use `$dateField.attr( "value", null )` instead of `_clearDate`. – Joshua Pinter May 29 '19 at 15:40
  • It's a very bad practice to use private variables. As the variable name implies it is private to the provider (i.e. JQuery) and they can update or remove at anytime without notice. Public API on the other hand goes through announcements before being changed - giving you ample to time update your app. – Stack Undefined Jun 28 '21 at 14:42
76

Did you try:

$('selector').datepicker('setDate', null);

That should work according to the API documentation

DavidWainwright
  • 2,895
  • 1
  • 27
  • 30
  • I have a form with some datepicker input I use to edit some date that I want to fill according to current date. I find this solution to reset my editing form before using "setDate" with the current date, but I have a format problem : without the `('setDate', null)` I have the format I want **(DD/MM/YYYY)**, but when I use it I have **MM/DD/YYYY**...the only difference is the use of `('setDate', null)`, any idea why? – Mickaël Leger Dec 18 '17 at 17:34
  • Sorry Mickael - I don't know about that. Have you tried resetting the format after setting the date to null as per https://stackoverflow.com/questions/1328025/jquery-ui-datepicker-change-date-format? – DavidWainwright May 31 '19 at 09:55
24

you just need to set the options again to null:

dates.datepicker( "option" , {
    minDate: null,
    maxDate: null} );

I've changed your jsfiddle: http://jsfiddle.net/tF5MH/9/

Simon Wang
  • 2,843
  • 1
  • 16
  • 32
  • yep, thanks. you're correct. It's funny, this issue even exists on the jQuery UI Datepicker Demo page. http://jqueryui.com/demos/datepicker/#date-range Set the to date, then empty the textbox and the problem exists – Cory Danielson Feb 24 '12 at 17:51
  • 1
    This is the cleanest way, for sure. `date.datepicker( "option" , {setDate: null, minDate: null, maxDate: null} );` – AL3X Jan 31 '17 at 21:48
14
$('.date').datepicker('setDate', null);
Baby Groot
  • 4,637
  • 39
  • 52
  • 71
Soni Sharma
  • 141
  • 1
  • 2
11

Try changing the clearing code to:

$('#clearDates').on('click', function(){
    dates.attr('value', '');
    $("input[id$='dpFrom'], input[id$='dpTo']").datepicker( "option", "maxDate", null );
    $("input[id$='dpFrom'], input[id$='dpTo']").datepicker( "option", "minDate", null );
});
j08691
  • 204,283
  • 31
  • 260
  • 272
10

Try This, This Will Add Clear Button On Jquery Calender That Will Clear Date.

$("#DateField").datepicker({
    showButtonPanel: true,
    closeText: 'Clear',
         onClose: function (dateText, inst) {
        if ($(window.event.srcElement).hasClass('ui-datepicker-close'))
        {
            document.getElementById(this.id).value = '';
        }
    }
});
sohaib
  • 837
  • 1
  • 12
  • 10
  • 1
    This answer is probably better than the others even though it doesn't work in Firefox. And replacing `document.getElementById(this.id).value = '';` with `$(this).val('').change();` makes it even better because then any established change handlers also get called. – Ryan Aug 15 '16 at 00:08
4

I know it's a bit too late, but here's a simple peace of code that did it for me:

$('#datepicker-input').val('').datepicker("refresh");
Miguel BinPar
  • 429
  • 4
  • 11
  • I can't see that refresh does any extra. You can just clear the value. – omarjebari Sep 02 '16 at 23:50
  • 1
    I like that you are using a public call vs. private function to clear the control. – snowYetis Nov 11 '16 at 15:52
  • 1
    @Miguel BinPar , I know this post is old but your answer is the only answer that worked for me after 3 days of trying to figure this out. Thanks! – kejo Oct 11 '20 at 18:51
3

The obvious answer was the one that worked for me.

$('#datepicker').val('');

where $('#datepicker') is the id of the input element.

omarjebari
  • 4,861
  • 3
  • 34
  • 32
  • I tried that solution in the JSFiddle, and it didn't work. http://jsfiddle.net/tF5MH/407/ See the reproduction steps below the inputs. Using `.val('')` will empty the inputs, but not clear out the datepicker restrictions in the calendars. – Cory Danielson Sep 05 '16 at 17:40
  • I also tried with the latest version of jQuery UI (v1.12.0), and it didn't work. – Cory Danielson Sep 05 '16 at 17:52
  • Thanks a ton omar. I have been searching this working solution from last 20 minutes. you are a life saver man!.. – Mahesh Apr 02 '20 at 21:07
3

Reset the max date attributes on your datepicker when you click clear.

From jquery website

Get or set the maxDate option, after init.

    //getter
    var maxDate = $( ".selector" ).datepicker( "option", "maxDate" );
    //setter
    $( ".selector" ).datepicker( "option", "maxDate", '+1m +1w' );
Mark W
  • 5,824
  • 15
  • 59
  • 97
  • Yes, you're correct. I marked j08691's as best answer because he gave me some code I could slap into the fiddle that worked. Unfortunately I couldn't mark them both as best :/ – Cory Danielson Feb 24 '12 at 17:40
  • Yes I know, I was going to explain it a bit better with some code relative to your problem, but he beat me to it. :) – Mark W Feb 24 '12 at 17:43
0

A modified version of Leniel Macaferi's solution to account for the backspace key being a "page back" shortcut in IE8 when a text field does not have focus (which appears to be the case when datepicker is open).

It also uses val() to clear the field since _clearDate(this) did not work for me.

$("#clearDates").datepicker().keyup(function (e) {
    // allow delete key (46) to clear the field
    if (e.keyCode == 46)
        $(this).val("");

    // backspace key (8) causes 'page back' in IE8 when text field
    // does not have focus, Bad IE!!
    if (e.keyCode == 8)
        e.stopPropagation();
});
Kidquick
  • 1,102
  • 12
  • 13
0

My datepicker initialization looks like:

    dateOptions = {
                changeYear: true,
                changeMonth: true,
                dateFormat: 'dd/mm/yy',
                showButtonPanel: true,
                closeText: 'Clear',
            };

So, the default 'Done' button will have 'Clear' text.

Now, inside datepicker.js find internal function '_attachHandlers' It looks like:

 _attachHandlers: function (inst) {
            var stepMonths = this._get(inst, "stepMonths"),
                id = "#" + inst.id.replace(/\\\\/g, "\\");
            inst.dpDiv.find("[data-handler]").map(function () {
                var handler = {
                    prev: function () {...},
                    next: function () {...},
                    hide: function () {
                        $.datepicker._hideDatepicker();
                    },
                    today: function () {...}
                    ... 

And change hide function to look like:

                   ...
                   hide: function () {
                        $.datepicker._clearDate(id);
                        $.datepicker._hideDatepicker();
                    },
                    ...

The solution came from this *data-handler="hide"*

0

I use this code to clear the field and all shenannigans. I Needed an empty field for my use case

jQuery.datepicker._clearDate(window.firstDay);
window.firstDay.datepicker('setDate',null);
window.firstDay[0].value = '';

For some reason .val('') wouldn't work for me. But bypassing jQuery did it. In my opinion its a flaw that there is no .datepicker('clear') option.

Tschallacka
  • 27,901
  • 14
  • 88
  • 133
0

My way to solve this problem

Change var 'controls' on ui.js

controls = (!inst.inline ? "<button type='button' class='ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all' data-handler='hide' data-event='click'>" +
        this._get(inst, "closeText") + "</button>" + "<button type='button' class='ui-datepicker-close ui-datepicker-clear ui-state-default ui-priority-primary ui-corner-all' data-handler='hide' data-event='click'>" +
        this._get(inst, "clearText") + "</button>" : "");

Then add a clearText var

    this.regional[""] = { // Default regional settings
    closeText: "Done", // Display text for close link
    clearText: "Clear", // Display text for close link
    prevText: "Prev", // Display text for previous month link

And before show function

$(".i_date").datepicker
(
    {
        beforeShow: function (input, inst)
        {
            setTimeout
            (
                function () 
                { 
                    $('.ui-datepicker-clear').bind('click', function() { $(input).val(''); });
                }, 
                0
            );
        }
    }
);
0
$("#datepicker").datepicker({            
        showButtonPanel: true,
        closeText: 'Clear', 
        onClose: function () {
            var event = arguments.callee.caller.caller.arguments[0];                
            if ($(event.delegateTarget).hasClass('ui-datepicker-close')) {
                $(this).val('');
            }
        }
    });
0

In Firefox it does job for me in form (programmatically), where datepicker control is disabled by default:

$("#txtDat2").prop('disabled', false); //temporary enable controls<br>
$("#txtDat2").val("YYYY-MM-DD"); //reset date to dd.mm.yyyyy
$("#txtDat2").prop('disabled', true); //back to default state
Isma
  • 67
  • 6
0

This code works for me

onClose: () => $("#datepicker-id").multiDatesPicker("resetDate"), 
Vishnu P
  • 11
  • 2
-1

Please try this solution it will work properly as I have tried

$('selector').datepicker('setStartDate', 0);

 $('selector').datepicker('setEndDate', 0);
$('selector').datepicker('update');
gaurav bhatt
  • 23
  • 2
  • 12