- Previous
- Next
- Alert Box
- Confirm Box
- Prompt
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.
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.
<!DOCTYPE html>
<html>
<head>
<script type="text/JavaScript">
function message()
{
alert("This alert box was called with the onload event!");
}
</script>
<title>JavaScript - Exercise 03: Alert Box</title>
</head>
<body onload ="message()">
</body>
</html>
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.
In this page, when you click the button an alert box with message will popup immediately.
<!DOCTYPE html>
<html>
<head>
<script type="text/JavaScript">
function message()</span>
{
prompt("Good Job!);
}
</script>
<title>JavaScript - Exercise 03: Alert Box</title>
</head>
<body>
<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()>
</form>
</body>
</html>
Output Of Example#1
The output of example#1 is a popup with a message.
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.
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.