Jquery – DatePicker clear functionality

datepickerjquery

I have a field with a date picker (jQuery) in jsp page.

sample (DatePicker)

http://jqueryui.com/demos/datepicker/#icon-trigger

Page also has a "clear" button functionality, which clears all text fields on a page and the text inserted in those fields including the date chosen from the datepicker.

clear button code

<input type="button" name="buttonclear" id="buttonclear" class="buttonstyle_mid" value="Clear"
  onclick="javascript:clearData();" />

javascript clearData() Code (for Date Field)

document.getElementById("DateId").value = "";

Date field Code

<form:input id="DateId" path="date" class="dateInput" size="11" maxlength="10" readonly="true" />

jQuery DatePicker Code

 <script type="text/javascript">
        jQuery(function($) {
            $('.dateInput').datePicker();
            });
            $('#DateId').datePicker({
                startDate : '01/01/1970',
                endDate : (new Date()).asString()
            });     
    $('#DateId').bind('dpClosed', function(e, selectedDates) {
                var d = selectedDates[0];
                if (d) {
                    d = new Date(d);
                    $('#DateId1').dpSetStartDate(d.addDays(1).asString());
                }
            });
            $('#DateId1').bind('dpClosed', function(e, selectedDates) {
                var d = selectedDates[0];
                if (d) {
                    d = new Date(d);
                    $('#DateId').dpSetEndDate(d.addDays(-1).asString());
                }
            });
 </script>

My code has a major shortcoming. If I select 1st of august, 2011 from the date picker and click on "clear" button. The date field gets cleared but I can't choose the same date again (i.e 1st of august, 2011).

Clear button only clears the value inside the field, but It does not clear the date in the underlying DatePicker

I have googled a lot on this issue, but couldn't find a proper solution on this issue. Any help would really be appreciated.

Thanks

Best Answer

I think you need to add the following in your clearData() function:

$('.dateInput').datepicker( "setDate" , null );

This unsets the selected value in the date picker. By simply clearing the text field value as you're doing now, the date picker isn't being updated and so it gets out of sync with the text field value.

Related Topic