user2424370
user2424370

Reputation:

Datepicker set default date

I am trying to set default date for Jquery datepicker on init. Here is my html:

var content = "";
            content = "<table class=\"filter-table\">";
            content += "<tr><td><label for='startDate'>From </label></td><td><input name='startDate' id='startDate' class='date-picker' /></td></tr>";
            content += "<tr><td>&nbsp;</td></tr>";  
            content += "<tr><td><label for='endDate'>To </label></td><td><input name='endDate' id='endDate' class='date-picker'  /></td></tr>";             

And my JavaScript:

<script type="text/javascript">
    function showdatepicker() {
        $('.date-picker').datepicker( {
            changeMonth: true,
            changeYear: true,
            changeDay: true,
            showButtonPanel: true,
            dateFormat: 'yy-mm-dd',
            onClose: function(dateText, inst) { 
                var day = $("#ui-datepicker-div .ui-datepicker-day :selected").val();
                var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
                var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
                    $('#startDate').datepicker({defaultDate: -30});
                $('#endDate').datepicker({defaultDate: new Date()});
            }
        });
    }       
    </script>

What I am trying to do is set the date and show in the textbox when on load the page. The endDate should be current date whilst start date should be one month before. However, by using these codes, it does not display the date in textbox when first load.

I wonder why is it so. Thanks in advance.

Upvotes: 11

Views: 36159

Answers (2)

GregL
GregL

Reputation: 38151

I, like you, could not use a method on the datepicker to populate a default date in the input.

So instead, I made code using vanilla JS to calculate the default dates and format them to display in the textboxes.

Here is the JS I added:

function showdatepicker() {
    // same as yours
}

function populateDefaultValues() {
    var today = new Date();
    var month = today.getMonth() - 1,
        year = today.getFullYear();
    if (month < 0) {
        month = 11;
        year -= 1;
    }
    var oneMonthAgo = new Date(year, month, today.getDate());

    $('#startDate').val($.datepicker.formatDate('yy-mm-dd', today));
    $('#endDate').val($.datepicker.formatDate('yy-mm-dd', oneMonthAgo));
}

$(function() {
    populateDefaultValues();
    showdatepicker();
});

jsFiddle

Upvotes: 6

Wireblue
Wireblue

Reputation: 1509

Have a look at the defaultDate option. It provides exactly the features you need.

Because the default date options will vary for each datepicker you will need to initialise them separately (basically copy-paste, and tweak to suit).

http://api.jqueryui.com/datepicker/#option-defaultDate

Upvotes: 0

Related Questions