It is true that possibly the best way is to insert a form with the fields so that the user can insert their response. But it is true that in a didactic way it is easy to use a pop-up window or prompt in which the user can insert data.
In order to implement the example of how to request data with a prompt, we are going to make an example that asks the user for two numbers and returns the result by console. The first thing is to know the syntax of the .prompt () method
result = window.prompt (message, default);
We see that in the first field we put a message to show the user to request the information and that the second parameter is the default value that we want to give the user. It is important to understand that this value is the value that will appear in the dialog box and that if the user deletes it, it will not be assigned as a default value. We see that the result of invoking the .prompt () method
is assigned to a variable.
In this way, if we want to ask the user for a couple of numbers, we will have the following.
let value1 = prompt (“Give me the value 1”, 0);
let value2 = prompt (“Give me the value 2”, 0);
What will make our browser show something similar to the following:
It seems something simple and that does not take us further. But there are a couple of considerations to keep in mind. The first is that the content returned by the .prompt () method
is a text string. You can check it by doing a .typeof ()
about your result.
console.log (“The content of a prompt is of the type:” + typeof (value1));
That is why if we want to add the values as if they were numbers, we must convert them to integers with the .parseInt () method
let sum = parseInt (value1) + parseInt (value2);
There is a second consideration. And it is that although we have seen that the second parameter of the .prompt () method
allows us to give a default value, the user can delete it and leave the content as empty. So it will be good to carry out some additional control of its content, especially if we expect it to be a number and we want to add them.
So we could have something like this:
value1 = (value1 == “”)? “0”: value1;
value2 = (value2 == “”)? “0”: value2;