How do you programmatically clear HTML5 date fields?

Viewed 56532

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:

$('input[type=date]').val('');

$('input[type=date]').val('0000-00-00');

But neither of them work on the latest version of Chrome for PCs at least, haven't tried them with other browsers or platforms yet. Is there an API call or something that can clear date fields in a cross-browser way? Solutions I have searched for like this require the user to clear the date field whereas I need this to be done programmatically.

10 Answers

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 = "";

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 change the date as empty

$('#invoiceDate').val(new Date())
Related