JavaScript Window prompt() Method

The JavaScript Window prompt() method is used to display a prompt box that allows the user to enter a value. It takes two arguments: a string that is the prompt message, and an optional default value for the input field. It returns the value entered by the user, or null if the user cancels the prompt box.

Here are some examples of how the prompt() method can be used in JavaScript code:

  1. To display a simple prompt box with a default value, you can use the following code:
var value = window.prompt('Enter a value:', 'default value');

// the value entered by the user will be stored in the variable
  1. To display a prompt box with a password field, you can use the following code:
var value = window.prompt('Enter your password:', '', 'password');

// the password entered by the user will be stored in the variable
  1. To validate the value entered by the user, you can use the following code:
var value = window.prompt('Enter a number between 1 and 10:', '');

// check if the value is a number and within the correct range
if (isNaN(value) || value < 1 || value > 10) {
    alert('Invalid value, please try again.');
    value = null;
}

// the validated value will be stored in the variable

Overall, the prompt() method provides a convenient way to display a prompt box and collect user input. It can be used for tasks such as validation, authentication, or other operations that require user input.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: