In this demonstration we learn that how to use Java Script to display a message box to the user. In Java Script there are two types of message box for displaying information. One is known as “alert” and another one is known as “confirm”. If you want to display an alert or warning regarding programs then we use alert () method for displaying message box and if we want to take some confirmation from user then we use confirm () method for displaying message box.
Displaying message by using alert ()
Code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
function showMessage() {
alert("Wow! You have created first java script application.");
}
</script>
</head>
<body onload="showMessage()">
</body>
</html>
Here I had created a function named showMessage () which called at the load event of the body means to say at load event of the html document and display a message. Remember that for creating a function in java script I used function as a key word and onload is named of the event which is automatically called as well as html document is loaded.
Output of the following code snippet is as follows
Displaying message by using confirm () method
confirm (“<string message>”); method in java script is used to display confirm message box.
<head>
<title></title>
<script type="text/javascript">
function showMessage() {
confirm("Wow! You have created first confirm message box.");
}
</script>
</head>
<body onload="showMessage()">
</body>
</html>
Output of the following code snippet is as follows
Detecting which button is clicked in Confirm dialog box
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
function showMessage() {
var dd = confirm("Click any button to trace which button is clicked.");
if (dd == true) {
alert("You had clicked OK button on confirm dialog box.");
}
else {
alert("You had clicked Cancel button on confirm dialog box")
}
}
</script>
</head>
<body onload="showMessage()">
</body>
</html>
Amit Singh
25-Mar-2011