How do you programmatically clear HTML5 date fields?

后端 未结 10 1262
我在风中等你
我在风中等你 2020-12-11 16:18

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:

         


        
相关标签:
10条回答
  • 2020-12-11 16:24

    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>

    0 讨论(0)
  • 2020-12-11 16:24

    You can restore the placeholder;

    $('input[type=date]')[0].valueAsDate = '';
    
    0 讨论(0)
  • 2020-12-11 16:29
    document.getElementById("datePicker").valueAsDate = null;
    

    this line of code works with my browser (chrome) , didn't tested in other browsers

    0 讨论(0)
  • 2020-12-11 16:29

    You can change the date as empty

    $('#invoiceDate').val(new Date())
    
    0 讨论(0)
  • 2020-12-11 16:35

    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 = "";
    
    0 讨论(0)
  • 2020-12-11 16:39

    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;
    }
    
    0 讨论(0)
提交回复
热议问题