Search code examples
javascripthtmlloopscycle

How to count the input entered with cycle(loop) in javascript?


They want if you enter random number like 600 the program to print "It's made of three digits",they want to be with a cycle and the input to be taken from the user.We cannot use document.write(""); Sorry if already similar post exist i cannot find what i was looking for.Down there is part of my idea basically input,button and getting the input with document.getelementbyid and somehow to show it with inner html.Thanks in advance!

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>


    <p id="result">Hello, please enter a number and the program will show the number of digits
    the number is made of.</p>

    <input id="input1" name="x" placeholder="Enter a number " />

    <button onclick="result()">submit</button>

    <script>
function firstFunction() {
   var input = document.getElementById("input1");
   var result = result();

   document.getElementById("result").innerHTML = ;
   
}

function result(){

//function for the cycle


}
    


    </script>


</body>
</html>


Solution

  • Get number of digits with JavaScript

    It's already been done i don't see it before.

    function count_digits(n) {
    numDigits = 0;
    integers = Math.abs(n);
    
    while (integers > 0) {
        integers = (integers - integers % 10) / 10;
        numDigits++;
    }
    return numDigits;
    

    }