[ Web Proxy ]
URL:
Viewing: https://www.javascripttutorial.net/javascript-bom/javascript-prompt/ [Back]  [Original]

Learn JavaScript prompt By Practical Examples
Skip to content

JavaScript prompt

Summary: in this tutorial, you will learn how to use the JavaScript prompt() method to display a dialog with a message prompting for user input.

Introduction to JavaScript prompt() method

The prompt() is a method of the window object. The prompt() method instructs the web browser to display a dialog with a text, text input field, and two buttons OK and Cancel.

javascript prompt [javascript prompt]

The dialog prompts the user to enter some text and wait until the user either submits or cancels it. The following illustrates the syntax of the prompt() method:

let result = window.prompt(message, default);
Code language: JavaScript (javascript)

In this syntax:

The result is a string that contains the text entered by the user or null.

Like alert() and confirm(), the prompt() is modal and synchronous. In other words, the code execution stops when the dialog is displayed and resumes after the dialog has been dismissed.

JavaScript prompt() examples

Let’s take some examples to see how the prompt() works.

1) Display a prompt dialog

The following example uses the prompt() to display a dialog that prompts users for their favorite programming languages:

let lang = prompt('What is your favorite programming language?');

let feedback = lang.toLowerCase() === 'javascript' ? `It's great!` :
    `It's ${lang}`;

alert(feedback);Code language: JavaScript (javascript)

2) 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.

The following example uses prompt() to display a dialog that asks users for their ages. If users are 16 years old or above, they are eligible to join. Otherwise, they will not be.

let ageStr = prompt('How old are you?');
let age = Number(ageStr);

let feedback = age >= 16 ?
    'You're eligible to join.' :
    'You must be at least 16 year old to join.';

alert(feedback);Code language: PHP (php)

Summary

Was this tutorial helpful ?
Yes No
Search …:

Window

Location

Navigator

Screen

History

Copyright © 2009 - Present by JavaScript Tutorial Website. All Right Reserved.


Web Proxy Viewer  |  New URL  |  Original Page