html retern null count-up time

I am trying to create a timer upstart from a specific value

JS code

            <script type="text/javascript"> 
            var minutesLabel = document.getElementById("minutes");
            var secondsLabel = document.getElementById("seconds");
            var totalSeconds = 0;
            setInterval(setTime, 1000);
            function setTime() {
                ++totalSeconds;
                secondsLabel.innerHTML = pad(totalSeconds % 60);
                minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));
            }

            function pad(val) {
                var valString = val + "";
                if (valString.length < 2) {
                    return "0" + valString;
                }
                else {
                    return valString;
                }
            }
        </script>

HTML Code

<asp:Label ID="minutes" runat="server" Text="00"></asp:Label>:<asp:Label ID="seconds" runat="server" Text="00"></asp:Label>

Error Console and keep printing every 1 sec

Uncaught TypeError: secondsLabel is null
setTime https://localhost:44340/attendance:30

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

There is nothing wrong with the script, looks like it does not find your html elements for some reason. There must be something else going on, because following script runs perfectly in my browser as plain html file:

<body>
<asp:Label ID="minutes" runat="server" Text="00"></asp:Label>:<asp:Label ID="seconds" runat="server" Text="00"></asp:Label>
    
    <script type="text/javascript"> 

            var minutesLabel = document.getElementById("minutes");
            var secondsLabel = document.getElementById("seconds");
            var totalSeconds = 0;

            setInterval(setTime, 1000);
            function setTime() {
        
                ++totalSeconds;
                secondsLabel.innerHTML = pad(totalSeconds % 60);
                minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));
            }

            function pad(val) {
                var valString = val + "";
                if (valString.length < 2) {
                    return "0" + valString;
                }
                else {
                    return valString;
                }
            }
    </script>
</body>

Maybe you could try swapping tags with plain and see if problem goes away (sorry, i don’t know ASP and if it affects in your example).


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x