Javascript Prompt for Input
We have learned many methods to output or display a piece of information, for example, see the below code for different types of output methods. So, In this article, we will see about Javascript prompt for input.
Outputting method:
console.log("Hello World !")
alert("Javascript Outptting");
document.write("A way to display ouput")
All of these output methods are not very useful in a real-life application because just about every application that we interact with has different ways of getting information from its users. For example, register for an account, sign in, create an online profile, create a blog post, and so on. There are a number of different ways of capturing dynamic input from users for instance. When a user fills out a signup form they can capture what they typed browsers also provide a simple way of capturing input with javascript.
You can Use the prompt command as one of the ways to collect information from a site user, for ex. you can ask questions and get a response.
How to use prompt
Code:
prompt("How are you?");
Output:
In the above code, we have the prompt followed by a set of parentheses and semicolons. As I mentioned earlier, having this parenthesis means that this is a method, we call it a prompt method. Now, we can call all of the commands such as alert(), document.write(), and console.log() method. We can use the prompt method to ask a question from a user like the alert method, we provide a message as a string. For example, in the above, we have given the string value of “howareyou?” in the prompt command.
So, see the above output the prompt displays a diablog box with a question, much like the alert method but there’s also a text field where users can type. I type “iamfine” in the prompttinputbox and hit the “ok” button. Now, the question is what exactyle happened to the text, I just typed as it turns out the browser captures the user’s response and gives it back to the program. In programming speak, we can say the prompt method returns a value and we can store that value in a variable.
code:
const status prompt("How are you?");
document.write(status);
Output:
In the above code, we can create a variable name and its status and assign it to the prompt method. And also display the value of this variable to the document, so we can use document.write() method. Now, if you run the code, your input will be displayed in the document after you enter the input. We can also display the status value alert() or console.log() method.
The promp method gives you back the user’s response or the text they entered. Here, we are using the console to see what’s inside the status variable at this point in the program, that is the power of the variable. So, the prompt is a quick and easy way to capture user input.