Что значит prompt в javascript
Перейти к содержимому

Что значит prompt в javascript

  • автор:

Window prompt()

The prompt() method displays a dialog box that prompts the user for input.

The prompt() method returns the input value if the user clicks "OK", otherwise it returns null .

A prompt box is used if you want the user to input a value.

When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed.

Do not overuse this method. It prevents the user from accessing other parts of the page until the box is closed.

Interaction: alert, prompt, confirm

As we’ll be using the browser as our demo environment, let’s see a couple of functions to interact with the user: alert , prompt and confirm .

alert

This one we’ve seen already. It shows a message and waits for the user to press “OK”.

The mini-window with the message is called a modal window. The word “modal” means that the visitor can’t interact with the rest of the page, press other buttons, etc, until they have dealt with the window. In this case – until they press “OK”.

prompt

The function prompt accepts two arguments:

It shows a modal window with a text message, an input field for the visitor, and the buttons OK/Cancel.

title The text to show the visitor. default An optional second parameter, the initial value for the input field.

The square brackets around default in the syntax above denote that the parameter is optional, not required.

The visitor can type something in the prompt input field and press OK. Then we get that text in the result . Or they can cancel the input by pressing Cancel or hitting the Esc key, then we get null as the result .

The call to prompt returns the text from the input field or null if the input was canceled.

The second parameter is optional, but if we don’t supply it, Internet Explorer will insert the text "undefined" into the prompt.

Run this code in Internet Explorer to see:

So, for prompts to look good in IE, we recommend always providing the second argument:

confirm

The function confirm shows a modal window with a question and two buttons: OK and Cancel.

The result is true if OK is pressed and false otherwise.

Summary

We covered 3 browser-specific functions to interact with visitors:

alert shows a message. prompt shows a message asking the user to input text. It returns the text or, if Cancel button or Esc is clicked, null . confirm shows a message and waits for the user to press “OK” or “Cancel”. It returns true for OK and false for Cancel/ Esc .

All these methods are modal: they pause script execution and don’t allow the visitor to interact with the rest of the page until the window has been dismissed.

There are two limitations shared by all the methods above:

  1. The exact location of the modal window is determined by the browser. Usually, it’s in the center.
  2. The exact look of the window also depends on the browser. We can’t modify it.

That is the price for simplicity. There are other ways to show nicer windows and richer interaction with the visitor, but if “bells and whistles” do not matter much, these methods work just fine.

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

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:

  • The message is a string to display. If you omit it, nothing will display on the dialog.
  • The default is a string containing the default value of the text input field.

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:

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.

Функция prompt в JavaScript

Вы уже знаете о существовании функции alert , выводящей заданное сообщение на экран. Существует также похожая функция prompt , которая позволяет получить от пользователя какой-либо текст.

Давайте для примера спросим имя пользователя:

Запустите приведенный выше код, чтобы увидеть окошко, выводимое функцией prompt . Вбейте ваше имя и нажмите на кнопку. Если вы проделали все описанные выше манипуляции, то введенное вами имя попадет в наш скрипт.

Для того, чтобы получить доступ к введенному имени, результат работы функции prompt нужно присвоить в какую-нибудь переменную, например, вот так:

Давайте на следующей строке кода выведем на экран введенное ранее имя, воспользовавшись функцией alert :

Вы должны понимать, что при вызове функции prompt дальнейшее выполнение скрипта блокируется, пока не будут введены соответствующие данные. В общем-то, также работает и функция alert , только она ожидает нажатия на соответствующую кнопку.

Кстати, использовать переменную не обязательно:

Спросите возраст пользователя с помощью функции prompt . Выведите с помощью alert введенный пользователем возраст.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *