Automatically set selected date to altField when loading

I want to set the values โ€‹โ€‹of the datepicker field and altFieldwhen the page is loaded, and I was wondering if there is an option in datepicker for this automatically (i.e. without a call setDate).

I know that if I do something like this:

$("#date-div").datepicker({altField:"#date-input",altFormat:"yy-mm-dd", defaultDate:+7});

If it date-divis div, the default date is automatically added to the field date-inputwhen the page loads. But if I use a text field instead div, it does not set the values โ€‹โ€‹automatically (I have to call setDateon a separate line).

I'm just curious, I already implemented this by calling setDate, but I would like to know if there is something to do this automatically, and if not why? (since it works when using a div to display a calendar).

+5
source share
2 answers

It is best set to parse the defaultDatevalue altFieldusing a library like Moment.js , because the browser implementation for parsing dates is unreliable. For example, if your altFieldis the field before the datepicker field and in ISO 8601 format, you can do this:

$(this).datepicker({
    altField: $(this).prev(),
    altFormat: $.datepicker.ISO_8601,
    defaultDate: moment($(this).prev().val()).toDate()
});

When you open the calendar, only the default date will be set. If you also want to populate the datepicker field, you can do this after initializing the datepicker using the code above:

$(this).datepicker("setDate", moment($(this).prev().val()).toDate());
0
source

Not 100% elegant as it needs to be repeated, but it works for me:

$("#date-div").datepicker({altField:"#date-input",altFormat:"yy-mm-dd", defaultDate:$("#date-input").val()});
-2
source

All Articles