Sandra Schlichting
Sandra Schlichting

Reputation: 25986

How to not get datepicker to clear text field values?

I have a website that looks like this

where "Begin Date" and "End Date" are datepicker.

When generating the webpage I can fill in values in those fields, but adding datepicker to them as well, clears the values.

I initialize datepicker like so

$(function() {
    var dates = $("#from, #to").datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        numberOfMonths: 3,
        onSelect: function(selectedDate) {
            var option = this.id == "from" ? "minDate" : "maxDate",
            instance = $(this).data("datepicker"),
            date = $.datepicker.parseDate(
                instance.settings.dateFormat ||
                $.datepicker._defaults.dateFormat,
                selectedDate, instance.settings);
            dates.not(this).datepicker("option", option, date);
        }
    });


    $("#from, #to").datepicker("option", "dateFormat", "dd/mm-yy");
});

and the HTML looks like

<input class="new" type="text" id="from" name="from"/>

How do I get datepicker to not clear the form field values when the webpage is loaded?

Upvotes: 4

Views: 3260

Answers (1)

marcosfromero
marcosfromero

Reputation: 2853

Don't know exactly why but it has to do with your onSelect function. I think you're expecting a special dateFormat and, given that your initial value doesn't have that format, datepicker just drops the value.

If you, however, set the dateFormat initially matching the initial value of your input, you won't have any problem.

Working example: http://jsfiddle.net/marcosfromero/3MG9D/

Upvotes: 1

Related Questions