-1

I'm trying to create a working time clock that allows me to input the number of hours I study everyday and get the total. Am I using parseInt wrong?

   <html>
     <head>
      <title>Time clock</title>
      <meta charset="utf-8">

     </head>
     <body>

        <h1 id="header">Time clock</h1>
        <p id="greeting"></p>
        <input type="text" id="inp"/>
        <button onclick="sumit()">Click</button>
        <p id="hours"></p>


       <script>
         greeting.innerHTML = 'How many hours have you studied?'

         function sumit(){
         let text = parseInt(document.getElementById("inp").value);
         let hours = (document.getElementById("hours"));
         let total = 0

         for (i = 0; i < 10; i++){
          total += parseInt(text[i]);


        hours.innerHTML = `You have studied a total of ${text + total} hours.`

         }
          console.log(total)
          console.log(text) 
        }

       </script>
      </body>
    </html>
cyrogen
  • 1
  • 1

2 Answers2

0

The text variable is already defined and assigned the value of parseInt. So your total += parseInt(text[i]) is trying to index a number type (e.g. total += 123[0]) which isn't possible. Instead, you can just do total += text, or you can remove the parseInt call when you declare text and then do total += parseInt(text).

Matt U
  • 4,970
  • 9
  • 28
0

With minimal changes, this should work:

      function sumit() {
        let text = parseInt(document.getElementById("inp").value) || 0;
        let hours = document.getElementById("hours");
        let total = 0;

        total += text;

        hours.innerHTML = `You have studied a total of ${total} hours.`;
      }

Explanation

  • parseInt can return NaN, so we use the || operator to let it default to 0
  • You don't need to loop over anything to sum the number
    • Even if you were looping over anything, you don't use reference indexes on numbers like you tried to do with text[i]
  • You don't need to add total to text multiple times
xyhhx
  • 6,384
  • 6
  • 41
  • 64