lily lily - 6 months ago 62
jQuery Question

Datepicker change date fires twice

I'm facing this issue where the date change fires twice, the user picks a date and the date would be in the format "

dd-mm-yyyy
" but when the user clicks out the date field or changes the date, it would change to "
YYYY-MM-DD
" (I need it to be in this format at submission)

I'm not sure what I'm doing wrong here.

Relevant Code:

<input type="text" data-bind="value: DateOfBirth" value="" required="" name="DateOfBirth" id="DateOfBirth" placeholder="dd/mm/yyyy" data-val-required="Date of Birth is required." data-val="true" autocomplete="off"class="form-control input-sm datepicker" aria-required="true" onkeydown="return false" />

<script>
$('.datepicker').datepicker({
startView: "decade",
minViewMode: "days",
format: "dd/mm/yyyy",
autoclose: true,
endDate : '0'
});

$('#DateOfBirth').change(function ()
{
var date = $(this).val();
if (date != null && date != "")
{
var dateArray = date.split('/');
if (dateArray.length === 3)
{
myModel.DateOfBirth(dateArray[2] + "-" + dateArray[1] + "-" + dateArray[0]);
}
}
$(this).valid();
});

</script>

Answer

I managed to fix it by using jquery-ui,

<input type="text" data-bind="value: DateOfBirth" value="" required="" name="DateOfBirth" id="DateOfBirth" placeholder="dd/mm/yyyy" data-val-required="Date of Birth is required." data-val="true" autocomplete="off"class="form-control input-sm datepicker" aria-required="true" onkeydown="return false"  />

<input type="hidden" id="BirthDate" value="" data-bind="value: DateOfBirth" />

<script>
        $(function () {

            $('#DateOfBirth').datepicker({
                format: 'dd/mm/yyyy',
                altField: "#BirthDate",
                altFormat: "yy-mm-dd"
            });

        $('#DateOfBirth').change(function () {
            var date = $("#BirthDate").val();
            if (date != null && date != "") {
                myModel.DateOfBirth(date);
            }
        });

</script>