Use the JavaScript prompt() method to show the prompt for input on the web page. The prompt() method instructs the web browser to display a dialog with a text, text input field, and two buttons OK and Cancel.
let input = prompt(message, default);
The prompt()
is a method of the window
object.
JavaScript prompt for input
Simple example code to enter some text in prompat input box by the user and submits or cancels it.
<!DOCTYPE html>
<html>
<body>
<script>
let lang = prompt('Favorite programming language?');
console.log(lang)
</script>
</body>
</html>
Output:
Convert a user input to a number
The result of the prompt()
is a string. If you want to get the answer as a number, you should always cast the string into a number.
<script>
let ageStr = prompt('How old are you?');
let age = Number(ageStr);
let feedback = age >= 16 ?
'Eligible.' : 'You must be at least 16 year';
console.log(feedback);
</script>
Do comment if you have any doubts or suggestions on this Js prompt topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version