RadeComet
RadeComet

Reputation: 31

jQuery change date format form

I have one function that needs to select dates and show it in link (after press button Submit) like this

?date_from=2018-09-18&date_to=2018-10-09

But problem is in input, where I have to select dates format is like 18-Sep-2018, so I have to format this 18-Sep-2018 to 2018-10-18, but still have to show like 18-Sep-2018 in input.

Here is the code

<form class="rates">
    <div class="date-range date-range-main">
        @include('components/input_date', [
            'name' => 'date_from',
            'inline' => TRUE,
            'value' => $date_range->get_start(),
            'label' => ''
        ])
        -
        @include('components/input_date', [
            'name' => 'date_to',
            'inline' => TRUE,
            'value' => $date_range->get_end(),
            'label' => ''
        ])
    </div>
    <button class="btn btn-primary" type="submit">
        {{uctrans('labels.search')}}
    </button>
</form>

So now when I run this function link is like

?date_from=30+Oct+2018&date_to=20+Nov+2018

and it needs to be like

?date_from=2018-11-20&date_to=2018-12-11

Upvotes: 3

Views: 753

Answers (1)

CodeThing
CodeThing

Reputation: 2768

Here you can do something like this.

$(document).on('submit', '.rates', function(e) {
    e.preventDefault;

    var form = $(document.createElement('form'));
    $(form).attr("action", "");

    var dt1 = new Date($('input[name="date_from"]').val());
    var dt2 = new Date($('input[name="date_from"]').val());

    var input1 = $("<input>").attr("type", "hidden").attr("name", "date_from").val(dt1.getFullYear() + "-" + (dt1.getMonth() + 1) + "-" + dt1.getDate());
    var input2 = $("<input>").attr("type", "hidden").attr("name", "date_to").val(dt2.getFullYear() + "-" + (dt2.getMonth() + 1) + "-" + dt2.getDate());

    $(form).append($(input1));
    $(form).append($(input2));

    form.appendTo( document.body );

    $(form).submit();

    return false;
}); 

In jquery we can create a hidden form and format the input and submit the new form.

Upvotes: 2

Related Questions