Basic JavaScript: Exercise 03 : Alert Boxes

Previous Article
Next Article

When a user makes mistake, the browser does not give feedback to users unless it is a server response or browser-based error. For example, when you cannot reach a web page, you receive HTML error 404 which means “web page not found“.

There are a lot of server-side errors, a common error is 503 and it means the server cannot provide the service requested. It gives a clear feedback- “Service unavailable“.

Browser-based scripting language such as JavaScript has its own way of giving feedback to users – “Dialog boxes”. There are 3 types of dialog boxes in JavaScript.

  1. Alert box
  2. Confirm box
  3. Prompt

In this example, we are only going to work on alert boxes.

JavaScript for Alert Box

#Example 1

An alert box is a popup box that is a result of an event. Any event like a click, double click, mouse move, etc. can result in an alert box.

So, the alert is an immediate feedback mechanism for some browser-based events.

function message()
alert("This alert box was called with the onload event!");
<title>JavaScript - Exercise 03: Alert Box</title>
<body onload ="message()">

As soon as the user loads the HTML page the associated JavaScript function will fired up and produce an alert box and give immediate feedback. In this program, the event is “onload” and alert is “The alert box was called with the onload event!”.

#Example 2

This is an example of an alert popup for a click event. When a user clicks the button on an HTML form page, an alert will give a message immediately, just like example 1 onload event. To create a page with button use HTML form tags.

<html> <head> <script type="text/javascript"> function message() { alert("Good Job!"); } </script>
<title>JavaScript - Exercise 03: Alert Box</title> </head>
<p> In this page, when you click the button an alert box with message will popup immediately.</p>
<form> <input type="submit" value="Click Me" onclick=message()>

Output of  #example 1

The output of example 1 is a popup with a message.

Output1: JavaScript Alert Box
Output1: JavaScript Alert Box

Output of #exercise 2

The example 2 HTML page has a form with a single button. When you click on the button an alert box will pop up.

This example shows how an alert box works for an onclick event.

Output 2: HTML page with button for #Example 2
Output 2: HTML page with button for #Example 2

When you click the button, the JavaScript function Рmessage() will execute. As a result, you will see the following alert box. There are many events in HTML to trigger a JavaScript program that does something like this.

Output 3: JavaScript Alert box for #Example 2
Output 3: JavaScript Alert box for #Example 2
Previous Article
Next Article