In this article we will talk about prompt in JavaScript, that is, windows that require a user to enter data.
The prompt () method therefore allows you to bring up windows to interact with the user.
prompt JavaScript – example 1
We want to make this example: when we click on the enter name button, the dialog box to enter the name will appear. After entering it and clicking ok, the greeting followed by the name just entered will appear in the level below.
Then try the example by clicking the button.
We then insert a button, anywhere on the page, which when clicked will bring up the dialog box for entering the name.
<button onclick=”myName()”>Insert the name</button>
In the div, which you can enter for example under button, I display the name that the user entered.
Let’s insert the JavaScript code now.
The JavaScript prompt () method has two arguments: the first that asks you to enter the name and the second that already appears in the field when the window opens (pre-filled value).
If the variable name is equal to the empty string then we display the message: ‘you have not entered the name’; otherwise we display the greeting followed by the name.
We are also using the getElementById () method which we will explore in the next articles.
function myName() {
var messagge;
var name = prompt("Insert your name:", "Coding Creativo");
if (name == null || name == "")
messagge = "You don't insert the name";
else
messagge = "Hi " + name;
document.getElementById("view").innerHTML = messagge;
}
prompt JavaScript – example 2
Let’s take another simple example now, using the prompt () method. For example, we calculate the age of a person after requesting entry through the dialog box.
We insert the button anywhere on our page.
<button onclick="myAge()">Age Calculator</button>
Then we build our script, using the prompt () method to get the user's birth year to be entered.
We then get the date of the day with the Date () object and store it in the myData variable. Then we use the getFullYear () method to get the current year from the myData and store it in a variable named myYear.
So, to get the age we simply make a difference between the current year and the year the user entered.
Here is the complete script that uses JavaScript prompt:
function myAge() {
var year = prompt("In what year were you born?", "1990");
if (year !== null) {
var myData = new Date();
var myYear = myData.getFullYear();
var age = (myYear - year);
if (age < 18)
alert("You are a minor, you have " + age + "years");
else
alert("You are of age, you have " + age + "years");
}
}
Of course these are just simple examples of using the prompt () method in JavaScript.
Some useful links
Introduction to JavaScript language
Learn JavaScript – basic concepts