Search code examples
javascripthtmlfunctiondominnerhtml

javascript dosen't read the value in html


So i want to make a program that start countingdown from a value that you choose but the issue is when i try to bring the value to javascript it dosen't work but when i type the value in html it work

here is my html code

<body>
<div id="count">
    <input id="time" type="number" min="0">
    <button id="button">Press here to begin the countdown</button>
</div>
<script src="lol.js"></script>

and here is my javascript code

var count = document.getElementById("count"),
    seconds = document.getElementById("time").value ,
    btn = document.getElementById("button"),
    secondPass;
    countDown = setInterval(function() {
        secondPass()
    } , 1000);
btn.onclick =         
function secondPass(){
    var minutes = Math.floor(seconds / 60),
        remseconds = seconds % 60;
    count.innerHTML = minutes + ":" + remseconds;
    if (remseconds < 10){
        remseconds = "0" + remseconds;
    }
    if (seconds> 0 ){
        seconds = seconds - 1;
    }   
    else {
        clearInterval(countDown)
        count.innerHTML = "done !"
    }
}

Solution

  • The problem in your code was that you were trying to get the value before it was entered. If I understood correctly, you wanted this:

    var count = document.getElementById("count"),
        btn = document.getElementById("button"),
        secondPass;
    
    
    btn.addEventListener("click", secondPass);
    
    function secondPass() {
        var seconds = document.getElementById("time").value
    
        var countDown = setInterval(function () {
            var minutes = Math.floor(seconds / 60),
                remseconds = seconds % 60;
            count.innerHTML = minutes + ":" + remseconds;
            if (remseconds < 10) {
                remseconds = "0" + remseconds;
            }
            if (seconds > 0) {
                seconds = seconds - 1;
            }
            else {
                clearInterval(countDown)
                count.innerHTML = "done !"
            }
        }, 1000);
    }
    <div id="count">
        <input id="time" type="number" min="0">
        <button id="button">Press here to begin the countdown</button>
    </div>