How do you programmatically clear HTML5 date fields?

后端 未结 10 1266
我在风中等你
我在风中等你 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: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;
    }
    

提交回复
热议问题