How to set input type date's default value to today?

后端 未结 30 3422
刺人心
刺人心 2020-11-22 14:00

The HTML5 input types are great, Opera\'s new built-in date picker is a breeze, and Chrome has at least supported the new input type with a spin-wheel implementation.

<
30条回答
  •  半阙折子戏
    2020-11-22 14:37

    The JavaScript Date object provides enough built-in support for the required format to avoid doing it manually:

    Add this for correct timezone support:

    Date.prototype.toDateInputValue = (function() {
        var local = new Date(this);
        local.setMinutes(this.getMinutes() - this.getTimezoneOffset());
        return local.toJSON().slice(0,10);
    });
    


    jQuery:

    $(document).ready( function() {
        $('#datePicker').val(new Date().toDateInputValue());
    });​
    


    Pure JS:

    document.getElementById('datePicker').value = new Date().toDateInputValue();
    

提交回复
热议问题