Skip to main content

JavaScript - Popup Boxes

JavaScript Popup Boxes


JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.


Alert Box


An alert box is often used if you want to make sure information comes through to the user.


When an alert box pops up, the user will have to click "OK" to proceed.


Syntax


window.alert("sometext");


The window.alert() method can be written without the window prefix.


Example


alert("I am an alert box!");

Confirm Box


A confirm box is often used if you want the user to verify or accept something.


When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed.


If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.


Syntax


window.confirm("sometext");


The window.confirm() method can be written without the window prefix.


Example


var r = confirm("Press a button");
if (r == true) {
    x = "You pressed OK!";
} else {
    x = "You pressed Cancel!";
}

Prompt Box


A prompt box is often used if you want the user to input a value before entering a page.


When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value.


If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null.


Syntax


window.prompt("sometext","defaultText");


The window.prompt() method can be written without the window prefix.


Example


var person = prompt("Please enter your name", "Harry Potter");
if (person != null) {
    document.getElementById("demo").innerHTML =
    "Hello " + person + "! How are you today?";
}

Line Breaks


To display line breaks inside a popup box, use a back-slash followed by the character n.


Example


alert("Hello\nHow are you?");

 


Comments

Popular posts from this blog

JavaScript Array Methods

JavaScript Arrays JavaScript arrays are used to store multiple values in a single variable. Displaying Arrays In this tutorial we will use a script to display arrays inside a <p> element with id="demo": Example < p  id= "demo" > < /p > < script > var cars = ["Saab", "Volvo", "BMW"]; document.getElementById("demo").innerHTML = cars; < /script > The first line (in the script) creates an array named cars. The second line "finds" the element with id="demo", and "displays" the array in the "innerHTML" of it. Example var cars = ["Saab", "Volvo", "BMW"]; Spaces and line breaks are not important. A declaration can span multiple lines: Example var cars = [     "Saab",     "Volvo",     "BMW" ]; Never put a comma after the last element (like &