Search code examples
javascriptdategetelementbyid

Javascript refresh time in HTML text box; getElementByID error


I am trying to have the time display every second in an HTML page, in a text box, but I just get the error message that getElementByID does not exist. My code is below. Nothing displays with the code below. can you please correct me, or point out what I am missing?

function getTime() {
     var currentDate = new Date();
     var date = currentDate.toLocaleString();
     document.getElementById("clock").innerHTML = date;
}

var repeatedTime = setInterval("getTime()", 1000);
getTime();

Here is my HTML code:

<!DOCTYPE html>
<html>
<head>
     <script src="clockjavascript.js" ></script>
</head>
<body>
    <form>
        <input id="clock" type="text" />
    </form>
</body>
</html>

Thank you to Daniel Szabo, for he solved this problem. The correct javascript which works with the HTML is below. I needed to change document.getElementById("clock").innerHTML to .value.

function getTime() {
    var dateObject = new Date();
    var dateString = dateObject.toLocaleString();
    document.getElementById("clock").value = dateString;
}

var repeatedTime = setInterval(getTime, 1000);
getTime();

Solution

  • Four issues

    • Use getElementById instead of getElementByID ("d" needs to be lowercase")
    • Use document.getElementById("clock").value instead of innerHTML to manipulate the contents of a textbox
    • Try setInterval(getTime, 1000); instead of setInterval("getTime()", 1000);
    • Move the <script src="clockjavascript.js"></script> tag to the bottom of the page, just before the </body> tag. That way the <input> element being acted upon is rendered and available to be acted upon when the script executes.

    For a quick test, you can paste this into your browser console and watch the time tick away.

    function getTime() {
       var currentDate = new Date();
       var date = currentDate.toLocaleString();
       console.log(date);
    }
    
    var repeatedTime = setInterval(getTime, 1000);
    getTime();