Javascript Aler Box


Javascript Pop up Boxes


Till now we have used only one kind of output statement - document.write. Javascript has few more "interactive" output statements in the form of Pop up Boxes. There are three types of Pop up Boxes - Alert box, Confirm Box and Prompt Box. Let us take a look at the Alert Box.

Alert Box


A javascript alert box pops-up with a message and an 'OK' button. It displays an alert box with a string passed to it. For example: alert() will display an empty dialog box with just the 'OK' button. The alert("Hello world") will display a dialog box with the message, 'Hello world' and an 'OK' button.

Let us look at the example that simply displays the "Hello World" pop up box when loaded.



  1. <html>
  2. <body>
  3. <script type="text/javascript">
  4. <!--
  5. /*
  6. ********************************************************
  7. Example Pop up Box - "Hello World"
  8. ********************************************************
  9. */
  10. alert("Hello world");
  11.  
  12. //-->
  13. </script>
  14. </body>
  15. </html>


You can try this example online at the link below, which will open in a new window.

Javascript Alert Box Example

Alert Box - Another Example - Day of week


Here is another example which will simply pop up an alert box which will display the day of week.



  1. <html>
  2. <body>
  3. <script type="text/javascript">
  4. <!--
  5. /*
  6. ********************************************************
  7. Example Pop up Box - "Day of week"
  8. ********************************************************
  9. */
  10. var day = new Date();
  11. myday = day.getDay();
  12. switch (myday)
  13. {
  14. case 0:
  15. alert("Today is Sunday");
  16. break;
  17. case 1:
  18. alert("Today is Monday");
  19. break;
  20. case 2:
  21. alert("Today is Tuesday");
  22. break;
  23. case 3:
  24. alert("Today is Wednesday");
  25. break;
  26. case 4:
  27. alert("Today is Thursday");
  28. break;
  29. case 5:
  30. alert("Today is Friday");
  31. break;
  32. default:
  33. alert("Today is Saturday");
  34. }
  35.  
  36.  
  37. //-->
  38. </script>
  39. </body>
  40. </html>




If you run the above script it should display the day of the week in a pop up box.

You can try this example online at the link below, which will open in a new window.

Javascript Alert Box - Day of week Example

Adding a new line in Alert Box



To add a new line in the alert box you can use \n. As an example

  1. alert("Hello world - This is line 1 \n This is line 2");


Will produce an alert box like



You could write the alert line more conviniently as

  1. alert("Hello world - This is line 1" + "\n" +"This is line 2");


In the next page we will take a look at javascript confirm box.