代码之家  ›  专栏  ›  技术社区  ›  Bernd

HTML5中的日期选择器设置当前日期

  •  0
  • Bernd  · 技术社区  · 6 年前

    我的HTML5日期选择器有问题。 我想用Javascript设置当前日期,但我总是知道应该如何提供日期。

    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
    <script>
    
    //Declare variables
    var today = new Date();
    
    // Set values
    $("#datePicker").val(getFormattedDate(today));
    
    // Get date formatted as YYYY-MM-DD
    function getFormattedDate (date) {
        return date.getFullYear()
            + "-"
            + ("0" + (date.getMonth() + 1)).slice(-2)
            + "-"
            + ("0" + date.getDate()).slice(-2);
    }
    
    </script>
    <title>Report</title>
    <body>
    
    <h1 align="center">Report f&uuml;r informative Ansichten</h1>
    
    <form action="#" th:action="@{/pdf}" method="post"> 
        <div><input name="datePicker" id="datePicker" type="date" min="1900-01-01" required></div>
        <span class="validity"></span>
        <input type="submit" value="PDF Ausgabe erzeugen"/>
    </form>
    </body>
    </html>
    

    也许有人能告诉我我做错了什么?

    提前谢谢。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Manuel Otto    6 年前

    $("#datePicker") 为空,因为尚未创建HTML。

    要么把脚本放在HTML下面,要么等待 $(document).ready()

    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <title>Report</title>
    </head>
    <body>
    
    <h1 align="center">Report f&uuml;r informative Ansichten</h1>
    
    <form action="#" th:action="@{/pdf}" method="post"> 
        <div><input name="datePicker" id="datePicker" type="date" min="1900-01-01" required></div>
        <span class="validity"></span>
        <input type="submit" value="PDF Ausgabe erzeugen"/>
    </form>
    
    
    <script>
    
    //Declare variables
    var today = new Date();
    
    // Set values
    $("#datePicker").val(getFormattedDate(today));
    
    // Get date formatted as YYYY-MM-DD
    function getFormattedDate (date) {
        return date.getFullYear()
            + "-"
            + ("0" + (date.getMonth() + 1)).slice(-2)
            + "-"
            + ("0" + date.getDate()).slice(-2);
    }
    
    </script>
    </body>
    </html>