I\'m looking for a way to programmatically clear HTML5 date fields with Javascript (specifically jQuery). So far I have tried two methods which I thought obvious:
I needed to do it recently and i've made this little hack... Seems to do the job.
It was just with JavaScript, but the jQuery version is pretty the same...
function reset_date_native() {
var date_input = document.getElementById('date-id');
//erase the input value
date_input.value = '';
//prevent error on older browsers (aka IE8)
if (date_input.type === 'date') {
//update the input content (visually)
date_input.type = 'text';
date_input.type = 'date';
}
}
function reset_date_jquery() {
$('#date-id').val('')
.attr('type', 'text')
.attr('type', 'date');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="date-id" type="date" />
<button onclick="reset_date_native()">Trigger the reset function (native)</button>
<button onclick="reset_date_jquery()">Trigger the reset function (jQuery)</button>
You can restore the placeholder;
$('input[type=date]')[0].valueAsDate = '';
document.getElementById("datePicker").valueAsDate = null;
this line of code works with my browser (chrome) , didn't tested in other browsers
You can change the date as empty
$('#invoiceDate').val(new Date())
If you can't clear a date field, this could also depend on a browser bug. I spend some time until I found out that you cannot reset the date in Firefox if the date control is disabled. See: https://bugzilla.mozilla.org/show_bug.cgi?id=1465979
Without the bug, I am able to clear the date like that:
document.getElementById("myDate").value = "";
This solution checks if a default value exists and, if so, uses it to reset the input. Otherwise, it clears the input it by updating value and valueAsDate.
Info on valueAsDate available at: w3c.org.
var dateEl = element.find('input#myDateInput[type="date"]');
dateEl[0].value = ('undefined' !== typeof dateEl[0].defaultValue) ? dateEl[0].defaultValue : '';
if (dateEl[0].value !== '') {
dateEl[0].valueAsDate = new Date(dateEl[0].value);
} else {
dateEl[0].valueAsDate = null;
}