You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

开发用户自定义日期倒计时网站时,获取HTML输入框日期值出现NaN问题的求助

Fixing the NaN Issue in Your User-Input Countdown Timer

Hey there! Let's get that countdown working with user-input dates instead of hardcoded values. Here's what's tripping you up, plus the fixed code:

What's Causing the NaN Values?

  • You're grabbing the element, not the value: Your line const newYears = document.getElementById("initialDate"); pulls the entire input element, not the date string the user typed. When you pass that element to new Date(), it can't parse it, resulting in an invalid date—and all your calculations turn to NaN.
  • Countdown runs before user input: The countdown() function fires immediately when the page loads, before the user has a chance to select a date. No valid date = NaN.
  • Your add() function doesn't update the countdown: Right now it just alerts the value, but doesn't connect that value to the timer logic.

Fixed Code with User Input Support

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Countdown Timer</title>
    <link rel="stylesheet" href="style.css" />
</head>
<body>
    <br><br><br>
    <div class="countdown-container">
        <div class="countdown-el days-c">
            <p class="big-text" id="days">0</p>
            <span>days</span>
        </div>
        <div class="countdown-el hours-c">
            <p class="big-text" id="hours">0</p>
            <span>hours</span>
        </div>
        <div class="countdown-el mins-c">
            <p class="big-text" id="mins">0</p>
            <span>mins</span>
        </div>
        <div class="countdown-el seconds-c">
            <p class="big-text" id="seconds">0</p>
            <span>seconds</span>
        </div>
        <div>
            <label for="myDate">
                <input type="date" name="myDate" id="initialDate">
                <button onclick="add()">Set Countdown Date</button>
            </label>
        </div>
    </div>
    <h1>...Until my Birthday</h1>
</body>
<script>
    // Store the user's target date here
    let targetDate = null;

    const daysEl = document.getElementById("days");
    const hoursEl = document.getElementById("hours");
    const minsEl = document.getElementById("mins");
    const secondsEl = document.getElementById("seconds");

    function add(){
        // Grab the actual value from the input field
        const inputDate = document.getElementById('initialDate').value;
        if(inputDate){
            targetDate = new Date(inputDate);
            alert("Countdown set to: " + targetDate.toDateString());
        } else {
            alert("Please select a valid date first!");
        }
    }

    function countdown() {
        // Only run calculations if we have a valid target date
        if(!targetDate){
            // Keep values at 0 if no date is set
            daysEl.innerHTML = "0";
            hoursEl.innerHTML = "00";
            minsEl.innerHTML = "00";
            secondsEl.innerHTML = "00";
            return;
        }

        const currentDate = new Date();
        const totalSeconds = (targetDate - currentDate) / 1000;

        // Handle cases where the target date has passed
        if(totalSeconds < 0){
            daysEl.innerHTML = "0";
            hoursEl.innerHTML = "00";
            minsEl.innerHTML = "00";
            secondsEl.innerHTML = "00";
            alert("The date you selected has already passed!");
            targetDate = null; // Reset the date
            return;
        }

        const days = Math.floor(totalSeconds / 3600 / 24);
        const hours = Math.floor(totalSeconds / 3600) % 24;
        const mins = Math.floor(totalSeconds / 60) % 60;
        const seconds = Math.floor(totalSeconds) % 60;

        daysEl.innerHTML = days;
        hoursEl.innerHTML = formatTime(hours);
        minsEl.innerHTML = formatTime(mins);
        secondsEl.innerHTML = formatTime(seconds);
    }

    function formatTime(time) {
        return time < 10 ? `0${time}` : time;
    }

    // Start the interval to update every second
    setInterval(countdown, 1000);
    // Run once initially to show 0 values
    countdown();
</script>
</html>

Key Changes Made:

  • Added a targetDate variable to store the user's selected date (as a Date object)
  • Modified add() to grab the input's .value and convert it to a valid Date, with checks for empty input
  • Updated countdown() to only calculate if a valid targetDate exists, and handle cases where the date has already passed
  • Removed the initial hardcoded element reference that was causing NaN

Now users can select a date, click the button, and the countdown will start updating correctly!

内容的提问来源于stack exchange,提问作者Athi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 23:34:06