Now one caveat before we dive into this subject…this function is not one I would suggest using often. There are some pitfalls with it, especially when it comes to validation of data. Nevertheless, it is a handy function to know when you want quick feedback. Here is how it works…
// Create variable to house end user info var userInfo;
// Prompt the user to enter information
userInfo = prompt("Please enter some information.");
// Output the end user’s information to the screen
document.write("You entered: " + userInfo);
So, as you can see from the code above, we can prompt the end user for some information. They can then enter that information. We can store it in a variable and then do what we would like to do with it. Below is what the end user would see when our code runs…
So, we can quickly and easily gather information from our users. I mentioned previously about some pitfalls with this. I will be honest, I do not use this too often because of the pitfalls. Forms are a better way of gathering the necessary information. Within a prompt, there is not a way to limit or dictate what the end user puts in. It is simply a text box with no parameters. Speaking of being a text box, numbers can be an issue. If you ask an end user to enter a number, that number comes across as a data type of string. So it needs to be converted to an integer using the Number() function.
With all of the issues and trappings that surround the prompt() that limits its usage, it is still a handy, quick little function in certain circumstances.