Getting user data by using prompt window in JavaScript
By using JavaScript prompt we can ask the visitor to enter data to our system for further processing. The prompt command will display a window and ask visitor to enter some data. We can collect the data entered by the user and store them in a variable. Here is some example.
var my_string = prompt("Please enter your name");
document.write(my_string)
We can show some default text while displaying the prompt. Here is an example where a default message is displayed for the visitor to enter first name.
var my_string = prompt("Please enter your name","enter your first name only");
document.write(my_string)
The above code will display the prompt window with some default text.
We can check the entered data by using if else condition.
Here is the demo of this code. Click the button below to display the prompt message.
<html>
<head>
<title>Demo of prompt window using JavaScript</title>
<script type="text/javascript">
function show_prompt() {
var my_string = prompt("Please enter your name","enter your first name only");
alert("Welcome "+my_string)
}
</script>
</head>
<body>
<br><br>
<input type=button value='Click here to display Prompt Window' OnClick="show_prompt()">
</body>
</html>
Instead of showing a Prompt we can display the message by using document.write()
<html>
<head>
<title>Demo of prompt window using JavaScript </title>
</head>
<body >
<br><br>
<input type=button value='Click here to display Prompt Window' OnClick="show_prompt()">
<script type="text/javascript">
function show_prompt() {
var my_string = prompt("Please enter your name","enter your first name only");
document.write("Welcome " + my_string)
document.write("<br><br>Return to <a href=window-prompt.php>tutorial on window prompt</a>");
}
</script>
</body>
</html>