Javascript - 从 HTML 输入中获取日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33659508/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:19:18  来源:igfitidea点击:

Javascript - get a date from an HTML input

javascripthtmldateinput

提问by Arnatuile

I am currently trying to take the value from an HTML input (below)

我目前正在尝试从 HTML 输入中获取值(如下)

<input type="date" id="dateInput" />

and put it into a javascript variable so I can use it for other things. I currently am using the code below.

并将其放入一个 javascript 变量中,以便我可以将其用于其他用途。我目前正在使用下面的代码。

    var input = document.getElementById("dateInput").value;
    var dateEntered = new Date(input);

But when I test those variables, it tells me that Inputis "" and dateEnteredis "Invalid Date".

但是当我测试这些变量时,它告诉我Input是“”,而dateEntered是“Invalid Date”。

I've tried the .valueAsDate instead of just .value as well. When I test those out, it tells me that Inputis null and dateEnteredis "Wed Dec 31 1969 19:00:00 GMT-0500 (Eastern Standard Time)" even though I entered today's date.

我也尝试过 .valueAsDate 而不是 .value 。当我测试它们时,它告诉我Input为 null 并且dateEntered是“Wed Dec 31 1969 19:00:00 GMT-0500(东部标准时间)”,即使我输入了今天的日期。

How would I fix this so that the javascript variables actually reflect the date I enter? I am using Google Chrome as my browser.

我将如何解决这个问题,以便 javascript 变量实际反映我输入的日期?我使用 Google Chrome 作为我的浏览器。

EDIT and UPDATEFor those who wanted my whole code, indentation is a little off sorry:

编辑和更新对于那些想要我的整个代码的人,缩进有点抱歉:

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8" />
   <meta name="viewport" content="width=device-width,initial-scale=1.0">
   <title>Calculate Time</title>
   <link rel="stylesheet" href="styles.css" />  
   <script src="modernizr.custom.05819.js"></script>
</head>
<body>
   <header>
      <h1> Calculate Time </h1>
   </header>
   <article align="center">
      <div id="cities">
          // My navigation links here (REMOVED)
      </div>
  <div id="caption">
     Calculate the time elapsed since a date entered.
  </div>
   <div class="box">
       <article>
           <form>
               <fieldset>
                   <label for="dateEntered">
                       Enter a Date
                   </label>
                   <input type="date" id="dateInput" />
               </fieldset>
               <fieldset class="button">
                   <button type="button" id="determineTime">Find Time</button>
               </fieldset>
               <fieldset>
                   <p>Time Elapsed is:</p>
                   <p id="time"></p>
               </fieldset>
           </form>
       </article>
   </div>
   <div id="map"></div>
  </article>
    <script>
        var input;
        var dateEntered;

        document.getElementById("dateInput").addEventListener("change", function () {
        input = this.value;
        dateEntered = new Date(input);
        });

    /* find and display time elapse */
    function lookUpTime() {
        // More code will go here later.
    }

    // add event listener to Find time button and clear form
    function createEventListener() {
        var submitButton = document.getElementById("determineTime");
        if (submitButton.addEventListener) {
            submitButton.addEventListener("click", lookUpTime, false);
        } else if (submitButton.attachEvent) {
            submitButton.attachEvent("onclick", lookUpTime);
        }
        document.getElementById("dateInput").value = "";
        // clear last starting value on reload
        document.getElementById("time").innerHTML = "";
        // clear previous results on reload
    }

    if (window.addEventListener) {
        window.addEventListener("load", createEventListener, false);
    } else if (window.attachEvent) {
        window.attachEvent("onload", createEventListener);
    }
</script>
<script src="script.js"></script>
</body>
</html>

回答by luanped

document.getElementById("dateInput").addEventListener("change", function() {
    var input = this.value;
    var dateEntered = new Date(input);
    console.log(input); //e.g. 2015-11-13
    console.log(dateEntered); //e.g. Fri Nov 13 2015 00:00:00 GMT+0000 (GMT Standard Time)
});

Basically you need to listen for the change of your date input, currently you were trying to get the value on load, when the picker has no date in it hence you get 'Invalid Date'

Basically you need to listen for the change of your date input, currently you were trying to get the value on load, when the picker has no date in it hence you get 'Invalid Date'

回答by rby

Make sure your script is executing after the DOM has fully loaded. To do this you can put your JS code in a function and call the function once the DOM has loaded, or just put your JS code at the end of your page, right before </body>.

确保您的脚本在 DOM 完全加载后执行。为此,您可以将 JS 代码放在一个函数中,并在 DOM 加载后调用该函数,或者将您的 JS 代码放在页面的末尾,就在</body>.