Create prompt dialog box and take dynamic input from user in JavaScript

In this tutorial, we will understand how to create a prompt dialog box and also how to take dynamic input from the user using prompt().

We will also save the entered prompt box data from the user in a JavaScript variable.

prompt() in JavaScript:

It displays a message box with Ok and Cancel buttons.

If Ok is clicked the text in input box is returned.

If Cancel is clicked null is returned.

Syntax:

prompt(message, default input)

Here default input is optional parameter.

For Example:

var country=prompt("Enter your country","India");
if(country==null || country.length==0){
console.log("you entered nothing");
 }
else{
console.log("you entered "+country);
}

Output:

Create prompt dialog box and take dynamic input from user in JavaScript

=> If we click ok without modifying the input then

Output: you entered India.

=> If we erase the default input then an empty string is returned.

Output: you entered nothing.

=>If we click cancel null will be returned.

Output: you entered nothing.

In this way, we can use the prompt() method to take dynamic input from the user.

The input taken from the user will be saved in a JavaScript variable.

Leave a Reply

Your email address will not be published. Required fields are marked *