In JavaScript, there are three basic operations that allow you to receive data from the user for further processing in scripts. These are alert, prompt and confirm. What they are used for, how to use them and other nuances will be discussed later in this article.

alert

It is used to display a modal window on the browser screen (this means that the user cannot click anything on the page until he closes this window. In this example, until he clicks "OK" in the window).

After displaying the message contained in the alert, the script execution is suspended and resumed after the modal window is closed.

In case of filling fields and clicking OK, the script will return the information that the user entered.

The syntax of this command somewhat more complicated than the previous one, since it allows you to set the text of the user's appeal and the contents of the field for entering information, which will be displayed by default: result = prompt(title, default) ;, where

  • title- a message that will be displayed to the user in the modal window. The argument is required.
  • default- what will be displayed in the text input field by default. It is also required to be filled in, because if it is not set, it may lead to errors in some browsers. If you want to leave the input field empty, then just set the prompt as follows:

    var myTest = prompt("Any info" , """);

Small prompt usage example:

var year = prompt( "What year did you graduate from high school?", 2008); alert("You are a graduate of " + year + " of the year!" ) ;

Typically, this command is used to collect data from users that the script needs to continue further work.

confirm

Also represents modal window. As it is not difficult to guess from the name, it is usually used to agree on something with the user.

Sharpened for that - for interaction, it provides the user with OK and CANCEL buttons, which return the boolean values ​​true and false to the script, respectively. Ratings: 4 (average 4 out of 5 )

In this lesson, we'll get to know the methods of the window object: alert() , prompt() , and confirm() .

alert() method

The alert() method is intended to display a warning dialog box with the specified message and an OK button on the user's screen. It can be used to convey important information to the user.

window.alert(Parameter_1);

The alert() method has one required parameter, which is the text of the message that is displayed in the dialog box. This method does not return anything as a result of its execution.

For example, let's display a warning dialog box for a site visitor when clicking on a link: Go to website

confirm() method

The confirm() method of the window object is intended to display a dialog box with the specified message and the OK and Cancel buttons on the user's screen. You can use the confirmation window to ask the user for permission to perform an action.

var resultConfirm = confirm(Parameter_1);

This method has one parameter - the text of the message that will be displayed in the dialog box.

The confirm() method returns one of two values ​​as the result (resultConfirm) of its execution:

  • true if the user clicked OK;
  • false if the user clicked Cancel or closed it.

For example, let's display in the p element with id="resultConfirm" the result of the user clicking on the "OK" button in the dialog box:

prompt() method

The prompt() method is designed to display a dialog box with a message, a text field for entering data, and "OK" and "Cancel" buttons on the user's screen. It is intended to request data from the user.

var resultPrompt = prompt(Parameter_1, Parameter_2);

This method has two parameters:

  • message to be displayed in the dialog box. This parameter is required and contains a message that "says" what data the user should enter in the text field;
  • the second parameter is optional and can be used to specify the initial value that will be displayed in the input field of the dialog box when opened.

Depending on the user's actions, the prompt() method can return the following data:

  • text value - if the input field contains data and the user clicked "OK";
  • empty string - if the input field does not contain data and the user clicked "OK";
  • null - if the user clicked "Cancel" or closed this window, it does not matter what data was entered in the text field.

Note: The dialog box that appears as a result of executing one of the alert() , confirm() , or prompt() methods is modal, i.e. it blocks the user's access to the parent application (browser) until the user closes the dialog box.

For example, we will ask the user for a name and, depending on the result, display the text in the element c id="nameUser" :

For example, let's ask the user to guess the number 8:

... Guess the number

In this article, we will explore three interesting methods, namely alert(), confirm() and prompt() methods. They all intended for user interaction.

All three of these methods belong to the window object. And they can be called like this: window.method_name(); But, JavaScript allows us not to specify this window object, but simply write the name of the method.

We'll start with the alert() method. This method displays the specified message in the user's browser window. This box will be displayed on top of the entire page, and until the user clicks on the OK button, it will not close.

To demonstrate, let's display some message using the alert () method.

var today_is = "Monday"; alert("Today is " + today_is);


Inside the method, we can specify any string, only without html tag ov. They are not processed here, but displayed as is.

If the string we want to specify is very long and we want to jump to new line, then here is the html tag
won't work. Here you need to use the character "\n".

Alert("Looooooooong \nStringgggggg");


This method is often used to find an error in the code.

The process of processing the code goes from top to bottom, so to catch an error, we simply write the alert () method in the intended area where the error is located. And if alert() worked, then there are no errors up to the line where it is written.

Next, you need to move it one line or more below. We save the changes, refresh the page in the browser again, and see if alert() worked, which means there are no errors before the line where it is located, otherwise, if it didn't work, the error is on the line above where it currently is. In this way, you can find an error in the code.

confirm() method

This method is used to confirm the answer to some question. There are only two answer options, yes (OK) or no (Cancel / Cancel). If the user answers yes, then the method returns true, otherwise it returns false.

For example, we will display a window using the confirm() method, where we will ask the user "Are you sure you want to leave the page?". If the user answers yes, then through the alert() method we will display such a message "The user wants to leave the page", otherwise we will display another message "The user does NOT want to leave the page".

Var user_answer = confirm("Are you sure you want to leave the page?"); if(user_answer) alert("The user wants to leave the page"); else alert("The user does NOT want to \nleave the page");


This is how the confirm() method works. It can be used in different occasions. For example, before deleting something from the site, it is customary to ask the user if he is sure of his actions. Or, before submitting the form, you can also ask the user "Did you fill out everything correctly?" If he answers yes, then the form will be sent, otherwise it will not be sent.

prompt() method

And the last method we will learn is the prompt() method. This method is used less frequently than the other two methods. It allows you to get some information from the user, which he will enter into the text field.

As a result, the prompt() method returns either the input string if the user clicked the OK button, or null if the user clicked the cancel button.

As a parameter, that is, inside the brackets this method we can write a prompt or a question to let the user know what information to enter.

For example, let's ask the user to answer the question "What is your name?". The name entered by the user will be displayed on the screen using the alert() method.

Varname = prompt("What is your name?"); alert("Your name is " + name);

Save and open the page in the browser.


Of course, any information can be entered into the text field from the prompt() method. This information will be returned as a string, even in the case of numbers or other special characters.

For example, let's ask the user to enter two numbers in order to multiply them later. There will be a calculator for multiplying numbers.

Var x = prompt("Enter the first number:"); var y = prompt("Enter the second number:"); //Convert the entered numbers from string type to numeric type x = Number(x); y = number(y); document.write(x + " * " + y + " = " + (x * y));

The entered numbers are strings, so for the correct result of multiplication, these numbers must be passed through the Number() function, which converts them from string type to normal numbers.

Well, that's all. Now you know three more methods: alert(), confirm() and prompt(). Which you can safely use in practice.

  • window object methods;
  • alert() method: short summary;
  • confirm() method - write letters;
  • prompt() method - let's get acquainted, I'm Stirlitz.

So, browser objects. And first of all - the oldest of them, the object window.

Here are the main methods of the object window(besides them, there are others, but they are of little use, and in order not to clutter up the brain with unnecessary information, I will postpone them until the third series).

Method

Description

Open and close browser windows; it is possible to determine the size of the window, its contents, as well as the presence keypad, address fields, and other attributes.

Appearance of an alarm dialog box with a corresponding message.

Appearance of a confirmation dialog box with "OK" and "Cancel" buttons.

The appearance of a prompt dialog box with a text input field.

Set or remove focus for a window.

Scrolls the contents of a window to a specific point.

Setting the time interval between a function call and expression evaluation.

Setting a one time interval before a function call or expression evaluation.

We already know that window often implied but not spelled.

Calling up various dialog boxes

Dialog boxes are used in programs to interact with the user.

alert() method

We analyzed it at the very beginning of our studies. It creates a simple dialog box with a message and an OK button. All its interaction is limited to the fact that the user, by pressing this single button, can send this window somewhere far away (and thanks for that).

confirm() method

Method confirm() already allows the user to make the simplest "boolean" decision: to say "yes" or "no".

For example, click this button:

Sorry for the little prank. I hope you know how to use the back button.

How is it all arranged? You, of course, saw that I have this method combined with alerts. And this is done with the help of the function that is inserted in .

The method returns two values: true(if OK) and false(if cancelled).

AT true we send it to the corresponding page (property href object location) and output the corresponding alert(). Otherwise (i.e. false) just output another alert().

And in the button we call the function in the event onClick:

And then you need to call this function from the event handler onSubmit tag

, for example:

"http://narod.yandex.ru/send-poll.xhtml" method="post" onSubmit= "return confirmAction()" >

Here, for example, you can write to me on the "soap" everything that you think about my lessons. If you suddenly got excited and pressed the button, and then it somehow became awkward, a dialogue window will pop up and sober you up.

If you're doing popups, it's good practice to warn the user and give them the choice to open the window or not. To do this, before loading the window, you need to release the "parliamenter" - dialog confirm(). Here the function is called from . We will talk about this very soon when we move on to creating windows using the method open().

prompt() method

This method already prompts the user for specific data. A dialog box appears with an input field. The method returns the data that the user entered in this field and allows the program to work with this data.

At the method prompt() two arguments: a question (which appears above the input field) and an answer (the text in the input field):

If you want the input field to appear clean, put empty quotes as the second argument:

prompt("question text","")

Let's see this in action. Press the button, don't be afraid.

So, you entered (or did not enter) data and received a response from the computer based on this data (or lack thereof).

Here is a simple version of this function:

Property innerHTML, which allows you to control the contents of the tag, we met in lesson 10, when we programmed the names under the pictures.

And here is the code for the button and the empty paragraph for the greeting.


But if you turned out to be my namesake, you saw that the function reacted to this as well.

How to do this in the "rough" version, you can already guess for yourself. Need to check variable username not only on empty quotes, but also on " Andrew", and add one more if with the appropriate text (you can practice yourself).

But if you type " Andrew", "Andryusha", "Andryushka", "Andryukha", "Andreyka", "Andrey Ivanovich", etc., then the result will be similar, although I did not explicitly go through all these values, but managed only five lines: " Andre", "Andrew", "Andrew", "Andreiche" and " Andreichu"(the last three - in order to exclude Andreev, Andreichenko and Andreichuk from the namesakes, while retaining Andreichik in the namesakes).

That is, you can guess that the function checks the variable username for the first 5, 6 or 8 characters.

But we will talk about this a little later, when we move on to string objects and their methods. I just want you to imagine in advance the tasks that we have to solve (in particular, all kinds of splitting strings into substrings). Then the decisions themselves will seem clearer. But if you can't wait, you can "copy" the function from the code and "cut it like a nut". For the curious, I wrote a comment there.

Method prompt() can also be used to enter a password.

This is not the end of the lesson!

Let's "play spy" a little to finish reading this chapter. First, try pressing the button and typing something.

Ah, that's it! But look, there is another button! Come on...

Password:

Press the first button again and enter the correct password.

All this fun, perhaps, has an effect, but in fact the password can be found by pressing right button and looking at it in code. Some may naively think that it is enough to put the code in a separate .js file. But in the page code there will be a link to this file with the address. And if you dial it in address bar, then a file with JavaScript code will open :)

Is it possible to encrypt the password in code? You can, but this again requires string manipulation along with the use of some mathematical methods. When we get to all this, we will also study the “real” password script. But the user interaction technique will still be the same: the method prompt(). (Is it possible to “crack” an encrypted password? Alas, there is no limit to the perfection of hackers ...)

In the same way as we “caught” the name or its absence, we will catch the password with the function.

If you enter an incorrect password or do not enter anything, the line

document.getElementById("no").style.display = "block"

opens the block with the second button

And if the correct password is entered, the action is transferred to the string

document.getElementById("yes").style.display = "block",

which opens the next block

Stop, what are those kryakozubry? This is a simple cipher, I will explain soon.

In the meantime, I give the code of these blocks (for clarity, I omit the table with frames, which I have enclosed in the last block):


"no" style="display: none;" >

Ah, that's it! But look, there is another button! Come on...




"mypassword" style="display: none;" >

Password:


Press the first button again and enter the correct password.



"yes" style="display: none;" >

Now we read further.


. . . . .
. . . . .

So, about encryption. She is very miserable. Any, knowing functions escape() and unescape(), will immediately hack it.

Function escape("enter string here") converts characters to their hexadecimal values.

Function unescape("insert quackaubers here") does the opposite.

To encrypt the password in this way, you need to drive it through at home escape(), copy the result and paste it into unescape(). But this, I repeat, is not serious.

Well, for complete set- function for the second button:

To display standard dialog boxes, JavaScript has only three methods that we learned today. Although these methods do not happen very often, the ability to use them confidently is extremely useful. They are simple, but at the same time they are, so to speak, “pure” programming. They are very good to fill your hand in mastering a programming language. And I advise you to experiment with them in every possible way, even if aimlessly from a pragmatic point of view. good programming- this is an exciting game, as, indeed, any creativity.