Home »
JavaScript Examples
JavaScript | Input value from the user using prompt
JavaScript Input value from the user using the prompt: In this tutorial, we will learn how to read values from the user using the prompt and print the input values in JavaScript?
By Pankaj Singh Last updated : July 30, 2023
Input value from the user using prompt
In JavaScript, you can use the prompt() method to take input from the user. In this method, you can provide the text that you want to display to the user. When the user inputs a value and presses the "ok" button, the input value is returned. You can store this value directly in a variable or parse it before storing it in a variable.
Example 1) Input name and print
To input name (string) in JavaScript using the prompt() method, you don't need to do extra because the prompt() method simply returns the string, just call the prompt() method by passing the text that you want to display. Store the value into a variable and print it.
Code (JS & HTML):
<!DOCTYPE html>
<HTML>
<HEAD>
<SCRIPT>
var name = prompt("Enter Your name:");
var msg = "Welcome "+name;
//alert(msg);
document.write(msg);
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>
Output
Example 2) Input an integer value and print it
To input numbers i.e., integer values in JavaScript using the prompt() method, you need to parse the input value because the prompt() method returns the string. To parse the prompt() method's returned value, you can use the parseInt() method, it accepts a string as a parameter and returns an integer value.
Code (JS & HTML):
<!DOCTYPE html>
<HTML>
<HEAD>
<SCRIPT>
var msg = prompt("Enter an integer value:");
var num = parseInt(msg)
document.write(msg);
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>
Output
Example 3) Input two numbers and find their sum
To input numbers i.e., integer values in JavaScript using the text boxes, you need to parse the input value because the text box returns the string. To parse the returned value, you can use the parseInt() method, it accepts a string as a parameter and returns an integer value.
Code (JS & HTML):
<!DOCTYPE html>
<HTML>
<HEAD>
<SCRIPT>
function Calculate(){
var a=parseInt(document.getElementById("txta").value);
var b=parseInt(document.getElementById("txtb").value);
var c=a+b;
document.getElementById("txtc").value=""+c;
}
</SCRIPT>
</HEAD>
<BODY>
<h2>The Sum Program</h2>
<hr />
<table>
<tr>
<td>
<label>Enter A:</label>
</td>
<td>
<input type="text" name="txta" id="txta" />
</td>
</tr>
<tr>
<td>
<label>Enter B:</label>
</td>
<td>
<input type="text" name="txtb" id="txtb" />
</td>
</tr>
<tr>
<td>
</td>
<td>
<input type="button" value="Calculate" onclick="Calculate()" />
</td>
</tr>
<tr>
<td>
<label>Sum</label>
</td>
<td>
<input type="text" name="txtc" id="txtc" readonly />
</td>
</tr>
</table>
</BODY>
</HTML>
Output
JavaScript Examples »