EnexoOnoma
EnexoOnoma

Reputation: 8836

Changing the format of textbox date to another textbox on the fly

I want a user to see a detailed date when he selects a day from the jQuery Datepicker. However the format I want to post and save in the database has to be different that the one showed.

As you see, the 2 textboxes have this DD, d MM yy format. This is what I want to show to the people so it stays that way. But for my code to work correctly, this date must be saved in the database in the format of Y-m-d (like 2012-03-23)

I want to avoid using PHP code after the form submits for the transformation. Maybe with a hidden field that automatically gets and transforms the value of #enarksi and #liksi ? After that I will post the hidden's fields value.

$(document).ready(function() {

    var date = new Date();
    var m = date.getMonth(),
        d = date.getDate(),
        y = date.getFullYear();

    $('#enarksi, #liksi').datepicker({
        minDate: new Date(y, m, d),
        dateFormat: 'DD, d MM yy'
    });

    $("#enarksi, #liksi").datepicker($.datepicker.regional["el"]);

});

Upvotes: 2

Views: 1051

Answers (1)

Laurent
Laurent

Reputation: 3837

Using the onSelect event of the datepicker, you can parse the date when it changes and set it to a hidden field.

$('#enarksi, #liksi').datepicker({
    minDate: new Date(y, m, d),
    dateFormat: 'DD, d MM yy',
    onSelect: function(selectedDate) {
        // Parse the selected date
        var instance = $(this).data('datepicker'),
            date = $.datepicker.parseDate(
                instance.settings.dateFormat ||
                $.datepicker._defaults.dateFormat,
                selectedDate, instance.settings);

        // Reformat
        var formatted = $.datepicker.formatDate('yy-mm-dd', date);

        // Set the formatted date
        $('#hiddenField').val(formatted);         
    }
});

You just need to find some way to select a hidden field. For example, you could use a data- attribute on your textboxes, such as data-hidden-field, and then just replace the last line of code with $('#' + $(this).data('hidden-field')).val(formatted);

Upvotes: 1

Related Questions