Getting Input from User / Keyboard in Java Script

Getting Input from User / Keyboard in Java script – Learn how to get input from user / keyboard like int, string and double data types etc in Java Script program. Example of taking integer / string input using prompt method in Java Script.

To get the input from user, we use predefined prompt method.

Prompt Read complete string including spaces.

Reading Two Integers input from user in Java script
Below program read two integers from user one by one. It prompt user to integer first and second number. The program displays the sum of both numbers entered by user. It will display the output as below

Output:

First Value : 10
Second Value: 20
Result      : Sum of First Number and Second Number is 30
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body onload="InputValues()">
    <pre>
        <b id="vld3"></b>
        <b id="vld5"></b>
    First Value : <b id="vld1"></b>
    Second Value: <b id="vld2"></b>
    Result      : Sum of First Number and Second Number is <b id="vld4"></b>
    </pre>
    <script>
        function InputValues()
        {
           
            var a = parseInt(prompt("Enter First Value"));
            if (isNaN(a))
            {
                document.getElementById("vld3").innerHTML = "First Value is not a Number";               
            }
            var b = parseInt(prompt("Enter Second Value"));
            if (isNaN(b))
            {
                document.getElementById("vld5").innerHTML = "Second Value is not a Number";
            }

            document.getElementById("vld1").innerHTML = a;
            document.getElementById("vld2").innerHTML = b;
            document.getElementById("vld4").innerHTML = a+b;
        }
    </script>
</body>
</html>



Leave a Comment