How to Add Reset/Clear Button in jQuery UI Datepicker

The jQuery UI Datepicker plugin is the easiest way to add datepicker to the input field using jQuery. It provides a datepicker dialog to select a date from the calendar view. When a text input field is used to attach a datepicker, the user can clear the selected value in the input field. But, if a non-editable HTML element or read-only input field is used, the selected datepicker value is not possible to clear manually.

In this example code, we will show you how to clear/reset the datepicker value using jQuery. We will add a Clear button to the datepicker dialog that allows resetting the selected value in jQuery UI Datepicker and clearing the selected date value from the input field.

HTML element to attach datepicker to text input.

<input type="text" id="datepicker" readonly="readonly">

The following code helps you to add a Clear or Reset button to the datepicker popup using jQuery.

  • The setCalsClearButton is a custom method that handles the Clear button operations.
  • Set showButtonPanel to true, to visible the button panel in the datepicker dialog.
  • Call the setCalsClearButton() function in beforeShow() event and onChangeMonthYear option.
$(function(){
    // Custom handler function
    var setCalsClearButton = function(year,month,elem){

        var afterShow = function(){
            var d = new $.Deferred();
            var cnt = 0;
            setTimeout(function(){
                if(elem.dpDiv[0].style.display === "block"){
                    d.resolve();
                }
                if(cnt >= 500){
                    d.reject("datepicker show timeout");
                }
                cnt++;
            },10);
            return d.promise();
        }();

        afterShow.done(function(){
            $('.ui-datepicker').css('z-index', 2000);

            var buttonPane = $( elem ).datepicker( "widget" ).find( ".ui-datepicker-buttonpane" );

            var btn = $('<button class="ui-datepicker-current ui-state-default ui-priority-primary ui-corner-all" type="button">Clear</button>');
            btn.off("click").on("click", function () {
                $.datepicker._clearDate( elem.input[0] );
            });
            btn.appendTo( buttonPane );
        });
    }

    // jQueryUI datepicker code
    $("#datepicker").datepicker({
        dateFormat: "yy-mm-dd",
        changeMonth: true,
        changeYear: true,
        showOn: 'focus',
        showButtonPanel: true,
        beforeShow : function(inst, elem){
            setCalsClearButton(null, null, elem);
        },
        onChangeMonthYear: setCalsClearButton
    });
});

Leave a reply

keyboard_double_arrow_up