Popup Window to Collect Input using prompt() function

 Syntax

The basic syntax of the prompt() function is as follows:

let result = prompt(title, [default]);

  • title: This is the text to display in the dialog box. It's a string that explains what type of input is expected from the user.

  • default (optional): This is the default value that appears in the input field of the dialog box. It's a convenient way to suggest an input value to the user.


Usage

When prompt() is called, it displays a modal dialog box with an optional message prompting the user to input some text, and two buttons: OK and Cancel.

  • If the user clicks OK, prompt() returns the input value as a string.

  • If the user clicks Cancel or presses the ESC key, prompt() returns null.


Popup looks like: 





Example 1: Basic Usage

let age = prompt("Please enter your age:", "18");

if (age !== null) {

    console.log(`You are ${age} years old.`);

} else {

    console.log("User cancelled the prompt.");

}


This example prompts the user to enter their age with a default value of "18". It then checks whether the user has provided input or cancelled the prompt.


Example 2: Input Validation

let quantity = prompt("Enter the quantity you want to order:", "1");


if (quantity === null) {

    console.log("Order cancelled.");

} else if (quantity === "" || Number(quantity) <= 0) {

    console.log("Please enter a valid quantity!");

} else {

    console.log(`You have ordered ${quantity} item(s).`);

}


In this example, the user is asked to enter a quantity for an order. The input is validated to ensure it is a positive number. If the input is invalid, an appropriate message is displayed.


Example 3: Looping Until Valid Input

let isValidInput = false;

let name = "";


while (!isValidInput) {

    name = prompt("What's your name?", "Harry Potter");

   

    if (name === null) {

        console.log("Prompt cancelled.");

        break; // Exit the loop if user cancels the prompt

    } else if (name.trim() === "") {

        alert("Please enter a valid name!");

    } else {

        isValidInput = true;

        console.log(`Hello, ${name}!`);

    }

}


This example demonstrates how to use a loop to repeatedly prompt the user until they provide a valid name. If the user cancels the prompt or enters a valid name, the loop terminates.

No comments:

Post a Comment