We are required to write a JavaScript program that provides user with a input. When the user inputs some value and press the button, our function should check if the input is a valid number,if it is a valid number, the program should print all digits of the number separately to the screen.
For example − If the input is −
43354
Then the output on the screen should be −
4 3 3 5 4
Let us write the code for this function −
The code for this will be −
HTML
<!DOCTYPE html> <html> <head> <meta charset="utf−8"> <meta name="viewport" content="width=device−width"> <title>Digits</title> </head> <body> <div class="column1"> <div class="input"> <button onclick="perform()"> Enter number </button> </div> <strong><div id="output"> </div></strong> </div> </body> </html>
JS
function perform() { var outputObj = document.getElementById("output"); var a = parseInt(prompt("Please enter a number: ", "")); var digit = ""; outputObj.innerHTML = "" while(a > 0){ let num = a%10 a = Math.floor(a/10) digit += "<p>"+num+"</p>" } outputObj.innerHTML = digit; document.getElementsByTagName("button")[0].setAttribute("disabled","true"); }
And the output on the screen will be −
After clicking OK button,