Mark Allison
Mark Allison

Reputation: 7228

How to select input date as default in JQuery datepicker?

I have an ASP.NET application which uses JQuery datepicker for picking dates in some text boxes. For some date textboxes, I populate the date textbox from my database. When this textbox is clicked my JQuery datepicker appears, and it shows the current month with Today highlighted. This is fine for empty textboxes, however sometimes the text box is populated from the database.

When the textbox is not empty I want the datepicker to show the textbox month and have the selected date to be the textbox date.

Is this possible?

Here's my current javascript code in my asp.net script header:

<script type="text/javascript">
    $(function () {
        $('#myTextBox').datepicker({
            dateFormat: 'dd-M-yy',
            numberOfMonths: 2,
            autoSize: true,
            changeMonth: true,
            changeYear: true,
            showButtonPanel: true,
            maxDate: 0
        });
    });  
</script>

Thanks, Mark.

Upvotes: 1

Views: 2140

Answers (2)

darioo
darioo

Reputation: 47183

You need to use defaultDate. Example:

<script type="text/javascript">
    $(function () {
        $('#myTextBox').datepicker({
            dateFormat: 'dd-M-yy',
            numberOfMonths: 2,
            autoSize: true,
            changeMonth: true,
            changeYear: true,
            showButtonPanel: true,
            maxDate: 0,
            defaultDate: new Date()
        });
    });  
</script>

This will initialize the default date to today's date. You need to add server side code that will initialize defaultDate to whatever you want.

Upvotes: 1

Skilldrick
Skilldrick

Reputation: 70819

You need to make sure that the format of your datepicker matches the format output by your serverside code. If they're exactly the same then it'll work. It won't try to parse the date if it's in a different format though.

Upvotes: 3

Related Questions