简体   繁体   中英

Why am I getting Null when I want to get a String from an HTML with JavaScript

I'm trying to build a memento mori kind of clock, and I want to make it so people can insert a certain date in there.

But when I get the element by ID in JS I get null.

Tried to get make it a string and test it with alerts, but I got no results. It was still null.

I mean, the alert box is empty, so I assume it is null.

Some of my assumptions are:

  1. There's a problem with the id or with the document.getElementById("targetDate").innerHTM part
    • I tried to get it as a string and then convert it to date as I did initially using this: new Date("Jan 5, 2090 15:37:25").getTime()
  2. I don't use the date functions the right way
  3. Maybe the approach should be changed to getting the day, month, year & hours separately

Here's the code:

HTML

<!DOCTYPE html>
<html lang="en" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title>💀 Days Until Death</title>
        <link rel="stylesheet" href="styles.css">
    </head>

    <body>
        <div class="main-div">
            <h2>💀 Days Until Death</h2>
            <hr>
            <h1><p id="demo"></p></h1>
            <hr>
            <input id="targetDate" type="input" name="date" value="Jan 1, 2090 15:37:25">
            <input onclick="ChangeDate()" type="submit" name="" value="Change Date">
        </div>

    </body>

    <script type="text/javascript" src="script.js"></script>
</html>

JavaScript:

// Set the date we're counting down to
var countDownDate = new Date("Jan 5, 2090 15:37:25").getTime();

function ChangeDate() {

    var targetDate = String(document.getElementById("targetDate").innerHTML);

    alert(targetDate);

    countDownDate = new Date(targetDate).getTime();
}

// Update the count down every 1 second
var x = setInterval(function() {

  // Get today's date and time
  var now = new Date().getTime();

  // Find the distance between now and the count down date
  var distance = countDownDate - now;

  // Time calculations for days, hours, minutes and seconds
  var days = Math.floor(distance / (1000 * 60 * 60 * 24));
  var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);

  // Display the result in the element with id="demo"
  document.getElementById("demo").innerHTML = days + "d " + hours + "h "
  + minutes + "m " + seconds + "s ";

  // If the count down is finished, write some text
  if (distance < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "EXPIRED";
  }
}, 1000);

I just replaced innerHTML to value

var targetDate = String(document.getElementById("targetDate").value);

And now I can get the date from the alert that you coded. Here's a screenshot: 在此处输入图像描述

You need to change innerHTML for value

Also don't need to convert it to String , and avoid using html inline event listeners

 // Set the date we're counting down to let countDownDate = new Date("Jan 5, 2090 15:37:25").getTime(); const demo = document.getElementById('demo'); const changeDateInput = document.getElementById('changeDateInput'); function ChangeDate() { const targetDate = document.getElementById('targetDate').value; console.log(targetDate); countDownDate = new Date(targetDate).getTime(); } changeDateInput.addEventListener('click', ChangeDate) // Update the count down every 1 second const x = setInterval(() => { // Get today's date and time const now = new Date().getTime(); // Find the distance between now and the count down date const distance = countDownDate - now; // Time calculations for days, hours, minutes and seconds const days = Math.floor(distance / (1000 * 60 * 60 * 24)); const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); const seconds = Math.floor((distance % (1000 * 60)) / 1000); // Display the result in the element with id="demo" demo.innerHTML = `${days}d ${hours}h ${minutes}m ${seconds}s `; // If the count down is finished, write some text if (distance < 0) { clearInterval(x); demo.innerHTML = "EXPIRED"; } }, 1000);
 <div class="main-div"> <h2>💀 Days Until Death</h2> <hr> <h1> <p id="demo"></p> </h1> <hr> <input id="targetDate" type="input" name="date" value="Jan 1, 2090 15:37:25"> <input id="changeDateInput" type="submit" name="" value="Change Date"> </div>

Try using document.querySelector instead, or you can also just get the method value instead of the innerHTML .

Also take a look on good practices with javascript by not using var for let and const .

https://hackernoon.com/why-you-shouldnt-use-var-anymore-f109a58b9b70 https://www.geeksforgeeks.org/what-is-the-disadvantage-of-using-innerhtml-in-javascript/

let countDownDate = new Date("Jan 5, 2090 15:37:25").getTime();

function ChangeDate() {
  const newTargetData = document.querySelector("#targetDate").value;

  alert(newTargetData);

  countDownDate = new Date(newTargetData).getTime();
}

// Update the count down every 1 second
const x = setInterval(function() {
  // Find the distance between now and the count down date
  const distance = countDownDate - Date.now();

  // Time calculations for days, hours, minutes and seconds
  const days = Math.floor(distance / (1000 * 60 * 60 * 24));
  const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  const seconds = Math.floor((distance % (1000 * 60)) / 1000);

  // Display the result in the element with id="demo"
  document.getElementById("demo").innerHTML = days + "d " + hours + "h "
  + minutes + "m " + seconds + "s ";

  // If the count down is finished, write some text
  if (distance < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "EXPIRED";
  }
}, 1000);

Good hacking for you buddy!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM