I am trying to change the default date format to DD/MM/YYYY. I have successfully did this. But it showing invalid date. When I select a date it's work well. But when I clear the date it's shows Invalid Date. How can I remove this error message.
$("input").on("change", function() {
this.setAttribute(
"data-date",
moment(this.value, "YYYY-MM-DD")
.format( this.getAttribute("data-date-format") )
)
}).trigger("change")
input {
position: relative;
width: 150px; height: 20px;
color: black;
}
input:before {
position: absolute;
top: 5px; left: 6px;
content: attr(data-date);
display: inline-block;
color: black;
}
input::-webkit-datetime-edit, input::-webkit-inner-spin-button, input::-webkit-clear-button {
display: none;
}
input::-webkit-calendar-picker-indicator {
position: absolute;
top: 16px;
right: 0;
color: black;
opacity: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>
<input type="date" data-date="" placeholder="s" data-date-format="DD/MM/YYYY" name="tckt_issue_date">
Updated Answer
The reason you were getting the invalid date error is because when you clear the date the input is passing an empty date to your jQuery function. When the value is given to the moment()
it returns an error because it expects a valid date.
So you need to test for an empty value.
Working code:
$('#datePicker').on('change', function() {
if(this.value){
$(this).attr('data-date', moment(this.value, 'YYYY-MM-DD').format($(this).attr('data-dateformat')));
} else{
$(this).attr('data-date', '');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>
<input id="datePicker" type="date" data-date="" placeholder="s" data-dateformat="DD/MM/YYYY" name="tckt_issue_date">
This code also properly updates the data-date attribute in the html.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments