I am trying to develop a website that will allow users to enter a date and then count down the number of days, hours,mins and seconds left till their chosen date.
I want users to enter their date using an html textbox if possible. I have a JavaScript variable const newYears =document.getElementById("initialDate")
, and I am trying to get it to extract data entered in my HTML textbox id=initiatDate
but it does not work when I do that. It just displays Nan values when I run it. When I give it a value.
Eg: const newYears ="30 Oct 2021"
it works fine. The problem is that I want the input to come from the user and not from me the designer. Below is my code
<!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" id="myDate" >
<input type="date" name="myDate" id="initialDate">
<button onclick="add()">Click to add date</button>
</div>
</div>
<h1>...Until my Birthday</h1>
</body>
<script>
function add(){
var a=document.getElementById('initialDate').value
alert("The value is "+a);
}
const daysEl = document.getElementById("days");
const hoursEl = document.getElementById("hours");
const minsEl = document.getElementById("mins");
const secondsEl = document.getElementById("seconds");
const newYears =document.getElementById("initialDate");
function countdown() {
const newYearsDate = new Date(newYears);
const currentDate = new Date();
const totalSeconds = (newYearsDate - currentDate) / 1000;
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;
}
countdown();
setInterval(countdown, 1000);
</script>