Javascript Simple Actions alert, prompt, confirm

Javascript Simple Actions alert, prompt, confirm

avaScript Simple Actions: alert(), prompt(), confirm()

JavaScript provides three built-in functions for simple user interactions:

1️⃣ alert() → Display a message
2️⃣ prompt() → Get user input
3️⃣ confirm() → Ask for confirmation

1️⃣ alert() – Display a Message

  • Used to show a simple pop-up with a message.
  • The user cannot provide input; they can only click "OK" to close the alert.

Example:

alert("Hello, welcome to my website!");

Use Case:

  • To show an important notification or warning.

2️⃣ prompt() – Get User Input

  • Displays a pop-up with a text input field.
  • The user can enter a value and click "OK" or "Cancel".
  • Returns the entered value (as a string) or null if the user clicks "Cancel".

Example:

let name = prompt("What is your name?"); alert("Hello, " + name + "!");

Use Case:

  • To collect user input, like names, numbers, or preferences.

šŸ”¹ Handling Default Values:

let age = prompt("Enter your age:", "18"); // Default value is 18 console.log("User age:", age);

šŸ”¹ Checking if Input is null (User Clicked Cancel):

let userInput = prompt("Enter something:"); if (userInput === null) { alert("You clicked cancel!"); } else { alert("You entered: " + userInput); }

3️⃣ confirm() – Ask for Confirmation

  • Displays a pop-up with "OK" and "Cancel" buttons.
  • Returns true if the user clicks "OK", otherwise returns false.

Example:

let isConfirmed = confirm("Do you want to proceed?"); if (isConfirmed) { alert("You chose OK!"); } else { alert("You clicked Cancel."); }

Use Case:

  • To confirm delete actions, logouts, or other important decisions.

šŸŽÆ Summary

FunctionPurposeReturn Value
alert()Displays a messageNothing (undefined)
prompt()Asks for user inputUser input as a string, or null if canceled
confirm()Asks for confirmationtrue if OK, false if Cancel

šŸš€ Now you're ready to interact with users in JavaScript! Let me know if you need more details. 😊

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close