Have an idea?

Visit Sawtooth Software Feedback to share your ideas on how we can improve our products.

Datepicker question

I chanced upon this sample code for datepicker:
<input type="text" id="datePicker" placeholder="dd/mm/yyyy">
<input name="FreeFormatQ_Unix" id="FreeFormatQ_Unix" type="hidden" value="">
<input name="FreeFormatQ_Year" id="FreeFormatQ_Year" type="hidden" value="">
<input name="FreeFormatQ_Month" id="FreeFormatQ_Month" type="hidden" value="">
<input name="FreeFormatQ_Day" id="FreeFormatQ_Day" type="hidden" value="">
<input name="FreeFormatQ_ReadableString" id="FreeFormatQ_ReadableString" type="hidden" value="">
 
<script>
$('#datePicker').datepicker({
    onClose: function(){
        var date = $('#datePicker').datepicker('getDate');
         
        // Unix
        $('#FreeFormatQ_Unix').val(date.getTime());
         
        // Y, M, D
        $('#FreeFormatQ_Year').val(date.getFullYear());
        $('#FreeFormatQ_Month').val(date.getMonth() + 1); // months are zero-based
        $('#FreeFormatQ_Day').val(date.getDate());
         
        // Readable string
        $('#FreeFormatQ_ReadableString').val($.datepicker.formatDate('MM d, yy', date));
    }
});
</script>

So when I click on the placeholder, it shows the calendar. If a choose a date, it works fine. But If I don't select a date and then close the calendar, it doesn't show up again even after I focus or put the cursor in the placeholder again. How do I make the calendar appear whenever I focus on the placeholder or text input?
asked Apr 9 by anonymous

1 Answer

0 votes
Looks like that code is missing the empty response case.  You could patch it up by replacing all those "$(...).val(...)" lines with this:

if (date) {
    $('#[% QuestionName() %]_Unix').val(date.getTime() / 1000);
    $('#[% QuestionName() %]_Year').val(date.getFullYear());
    $('#[% QuestionName() %]_Month').val(date.getMonth() + 1);
    $('#[% QuestionName() %]_Day').val(date.getDate());
    $('#[% QuestionName() %]_ReadableString').val($.datepicker.formatDate('MM d, yy', date));
}
else {
    $('#[% QuestionName() %]_Unix').val('');
    $('#[% QuestionName() %]_Year').val('');
    $('#[% QuestionName() %]_Month').val('');
    $('#[% QuestionName() %]_Day').val('');
    $('#[% QuestionName() %]_ReadableString').val('');
}


Or, alternatively, the latest Calendar question can be downloaded here:

https://sawtoothsoftware.com/community-question-library/1732-calendar
answered Apr 9 by Zachary Platinum Sawtooth Software, Inc. (121,525 points)
...