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

后端 未结 30 2994
刺人心
刺人心 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:13

    use moment.js to solve this issue in 2 lines, html5 date input type only accept "YYYY-MM-DD" this format. I solve my problem this way.

    var today = moment().format('YYYY-MM-DD');
     $('#datePicker').val(today);
    

    this is simplest way to solve this issue.

    0 讨论(0)
  • 2020-11-22 14:14

    this works for me:

    document.getElementById('datePicker').valueAsDate = new Date();
    

    https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement

    0 讨论(0)
  • 2020-11-22 14:14

    And for those using ASP VBScript

    <%
    'Generates date in yyyy-mm-dd format
    Function GetFormattedDate(setDate)
    strDate = CDate(setDate)
    strDay = DatePart("d", strDate)
    strMonth = DatePart("m", strDate)
    strYear = DatePart("yyyy", strDate)
    If strDay < 10 Then
      strDay = "0" & strDay
    End If
    If strMonth < 10 Then
      strMonth = "0" & strMonth
    End If
    GetFormattedDate = strYear & "-" & strMonth & "-" & strDay
    End Function
    %>
    

    And then in the body, your element should look something like this

    <input name="today" type="date" value="<%= GetFormattedDate(now) %>" />
    

    Cheers!

    0 讨论(0)
  • 2020-11-22 14:15

    Like any HTML input field, the browser will leave it empty unless a default value is specified with the value attribute.

    Unfortunately HTML5 doesn't provide a way of specifying 'today' in the value attribute (that I can see), only a RFC3339 valid date like 2011-09-29.

    TL;DR Use YYYY-MM-DD date format or it won't display

    0 讨论(0)
  • 2020-11-22 14:16

    by Javascript:

    var today = new Date();
    
    document.getElementById("theDate").value = today.getFullYear() + '-' + ('0' + (today.getMonth() + 1)).slice(-2) + '-' + ('0' + today.getDate()).slice(-2);
    
    0 讨论(0)
  • 2020-11-22 14:16

    Thanks peter, now i change my code.

    <input type='date' id='d1' name='d1'>
    
    <script type="text/javascript">
    var d1 = new Date();
    var y1= d1.getFullYear();
    var m1 = d1.getMonth()+1;
    if(m1<10)
        m1="0"+m1;
    var dt1 = d1.getDate();
    if(dt1<10)
    dt1 = "0"+dt1;
    var d2 = y1+"-"+m1+"-"+dt1;
    document.getElementById('d1').value=d2;
    </script>
    
    0 讨论(0)
提交回复
热议问题