0

I have a Datepicker that has this format set, and is associated with a textbox on my page (ASP MVC View):

$(function () {
            $("#MyDateTextbox").datepicker({
                dateFormat: "dd-M-yy",
                showOn: "button",               
                buttonImage: "@Model.BaseURLOfSite" + "/Images/calendar.gif",
                buttonText: "Calendar"
            });
        });

If the text field is originally empty, and I select a date from the control, and the date is saved in the dateFormat noted, when I click on my textbox again, the calendar opens to the date that was saved. Ex) "31-DEC-2020"

However, if text field already has a date with a format like "04/13/2020", a value that was saved to the text field (and database) before the picker was added to the page, when I click on the datepicker icon associated with the textbox, either the page locks up, or else the datepicker opens with today's date highlighted.

New dates set and saved with the datepicker control: no issue. Existing dates (in different format), and accessed by the datapicker control: there is the above problem.

1 Answer 1

1

There is a beforeShow option with Datepicker that I use for the following solution which can be viewed here.

For this, I took the existing value of the input element and convert it to a string that datepicker can interpret, then sets the date:

$(".datepicker").datepicker({
        dateFormat: "dd-M-yy",
        showOn: "button",               
        buttonText: "Calendar",
        beforeShow: function(ele, obj){

            // Current value
            var existing_date = $(ele).val();

            // If it contains a / then it's not formatted right
            if(existing_date.indexOf('/') > -1){

                // Using new Date and Date.parse gives us
                // Mon Apr 13 2020 00:00:00 GMT-0500 (Central Daylight Time)
                var new_date = new Date(Date.parse(existing_date));

                // Set the date
                $(ele).datepicker("setDate", new_date);

            }

        }
});

I'm not sure this is the best way to do it but it's a start. I hope it helps!

Sign up to request clarification or add additional context in comments.

1 Comment

This is working perfectly for me! I really appreciate your quick and very helpful response. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.