web
You’re offline. This is a read only version of the page.
close
Skip to main content
Community site session details

Community site session details

Session Id :

JavaScripting 101: Introduction to Notifications in JavaScript

Mitch Milam Profile Picture Mitch Milam

Within JavaScript, there are three different methods for displaying messages to the user and possible requesting input:

  • alert
  • confirm
  • prompt

 

Alert

The JavaScript alert function is the most commonly used notification method within JavaScript. Code like this:

alert("This is an alert.");

Produces the following dialog box:

image

This type of alert is used to simply inform the user of something. No other actions are available.

 

Confirm

The confirm function asks the user a question and returns a value of True for OK and False for Cancel. Here is the code:

var result = confirm("Press OK or Cancel");

if (result)
{
  alert("You pressed OK!");
}
else
{
  alert("You pressed Cancel!");
}

And here is the resulting dialog:

image

After the user makes a selection, you can take appropriate action using an if statement, as show above.

Note: Unfortunately, the OK and Cancel buttons cannot be changed. This means you may have to include verbiage that will instruct the user that OK actually means YES. [ insert your language-specific versions of these words here.]

 

Prompt

The final JavaSctipt notification is the Prompt function, which asks the user to input information.  Here is the code:

var nameOfIceCream = prompt("What type of ice cream fo you like?","Rocky Road");

if (nameOfIceCream != null && nameOfIceCream != "")
{
    alert("Wow! " + nameOfIceCream + " is my favorite as well.");
}

And here is the result:

image

Prompt takes two parameters:

  1. Prompt Text
  2. Default value [optional]

Note: Depending on your browser security settings, Prompt may actually cause a security alert to display. If this happens, you need to make sure that your web site is in the Local intranet or Trusted Sites security zones.

 

Tips

If you would like to have a multi-line prompt, you can obtain it by adding ‘\n’ where you would like the line to be placed onto the next line.

This code:

alert("You must either complete the field:\n\nFull name\n\nor the fields\n\nFirst Name and Last Name");

 

Produces the following dialog:

image

 

Additional Notes

One thing that is rather unfortunate, is the fact that we can’t change the title of the dialog box window, which is hard-coded by Internet Explorer. As you can see from the above examples, we have titles of: Message from webpage and Explorer User Prompt.

 

References

JavaScript Popup Boxes


This was originally posted here.

Comments

*This post is locked for comments