JavaScript alert()

The alert function in JavaScript serves the purpose of presenting a modal alert box. It is primarily utilized to convey warning messages to users. This function generates an alert dialog box that contains a designated message (which can be optional) along with an OK button. Once the dialog box appears on the screen, the user must click the OK button in order to continue.

The alert dialog box captures the user's attention and compels them to view the designated message. Therefore, it is advisable to use this technique sparingly, as it restricts the user's ability to interact with other sections of the webpage until the dialog is dismissed.

To illustrate the utility of the alert method, let’s consider an example. Imagine we need to complete a form for obtaining an identity card. The form requests the date of birth to determine eligibility for the identity card. If the individual is 18 years old or older, the application process will proceed. Conversely, if the individual is under 18 years of age, a warning message will be displayed indicating that the age is below 18 years. This warning message will appear in an Alert Box.

An additional illustration would be a scenario where a user must complete a form that includes certain obligatory fields necessitating the entry of specific text. If the user neglects to provide this information, we can implement validation by displaying an alert dialog box that presents a warning message concerning the need to fill in the text field.

In addition to displaying warnings or errors, the alert dialog box can also serve the purpose of conveying standard messages, such as 'Welcome back' or 'Hello XYZ', among others.

Syntax

Example

alert(message)

Value

message: This is an optional string that defines the text to be presented within the alert box. It contains the information that we wish to convey to the users.

Let's examine a few instances of the alert method in JavaScript.

Example 1: Simple alert dialog box

In this illustration, a basic alert dialog box is presented featuring a message along with an OK button. An HTML button serves the purpose of triggering the alert box. We utilize the onclick event attribute to invoke the fun function, within which the alert is implemented.

Example

Example

<html>  

   <head>     

      <script type = "text/javascript">  

            function fun() {  

 	 alert ("This is an alert dialog box");  

            }  

      </script>       

   </head>  

     

   <body>  

      <p> Click the following button to see the effect </p>        

      <form>  

         <input type = "button" value = "Click me" onclick = "fun();" />  

      </form>       

   </body>  

</html>

Output:

Upon pressing the button labeled Click me, the resulting output will be:

Explanation:

In the preceding example, a button labeled Click me is established within the form. Inside a JavaScript tag, a function referred to as fun is defined, which is responsible for generating an alert that displays a message. This message appears in a dialog box. We incorporated an onclick event attribute to this button. Upon loading the page, users will see the option to click me. When the button is clicked, the alert box is triggered.

Example 2: An alert box with a line break message

In this illustration, an alert dialog box is presented featuring a message along with an OK button. In this case, we incorporate line breaks within the alert box's message. The line breaks are specified using the '\n' character. These line breaks enhance the clarity and readability of the message. To observe the effect, one must click the provided button.

Example

Example

<html>

<head>

    <script type="text/javascript">

        function fun() {  

               alert ("Hello World \n Welcome to the logic-practice.com \n This is an alert dialog box");  

            }  

    </script>

</head>

<body>

    <p> Click the following button to see the effect </p>

    <form>

        <input type = "button" value = "Click me" onclick = "fun();" />

    </form>

</body>

</html>

Output:

After clicking the button, the output will be:

Explanation:

In the preceding example, we established HTML code. A button labeled Click Me has been incorporated within the form. In the JavaScript section, we defined a function called fun that triggers an alert displaying a message accompanied by an OK button. We included the onclick event attribute to this button. Upon loading the page, users will see the option to click me. When this button is clicked, a dialog box will emerge, presenting a message that includes a line break.

Example 3: Alerts before the page is loaded

In this illustration, we will present an alert notification as soon as the HTML document executes, prior to the user interacting with any other components on the webpage.

Example

Example

<html>

<head>



<script>

alert('Close this alert box by clicking the Ok button to see the page.');

</script>

</head>

<body>

<p>Hello World</p>

</body>

</html>

Output:

After clicking on OK, the output will be:

Explanation:

In the preceding example, we have written HTML markup. Within this markup, a JavaScript function is established, which triggers a JavaScript alert that is executed directly within the <script> tag prior to the loading of the page. Upon executing the page, the alert dialog appeared before the content was fully loaded, preventing any interaction with the page until the user pressed the Ok button. Once the user clicks the OK button, the content "Hello World" is then displayed on the page.

Example 4: Alert message using variables

An alert is capable of presenting not just static text but can also be employed to exhibit a variable value that has been defined within the file. To clarify this concept, let’s consider an example.

Example

Example

<html>

 <head>

   <script>

     function AlertMyVariable(){

        var myMessage="Alert Message!";

      alert(myMessage); 

     }

   </script>

 </head>

 <body>

   <form>

     <input type="button" value="See Alert" onclick="AlertMyVariable();"/>

   </form>

 </body>

</html>

Output:

After clicking on OK, the output will be:

Explanation:

In the preceding example, HTML code is established. Within this code, a form is incorporated, and a button titled See Alert is generated. A function called AlertMyVariable is defined in JavaScript. Within this function, we declare a variable named myMessage using var, which contains the text Alert Message! We employed the onClick event for the button.

Upon loading the webpage, the button labeled See Alert appears. When the user interacts with this button by clicking it, an alert box emerges, presenting the message, Alert Message.

Example 5: Displaying the URL of the Corresponding page in the Alert box

In this illustration, an alert dialog window is generated featuring a message alongside an OK button. The alert box displays the URL of the associated page. This URL is established using the statement alert(location.hostname);.

Example

Example

<html>

<head>

<script type="text/javascript">

function fun() {

alert(location.hostname);

}

</script>

</head>

<body>

<p> Click the following button to see the effect </p>

<form>

<input type = "button" value = "Click me" onclick = "fun();" />

</form>

</body>

</html>

Output:

After clicking on OK, the output will be:

Explanation:

In the preceding example, we established HTML code. A button labeled Click Me is incorporated within the form. We also created a function referred to as fun that generates an alert displaying a message accompanied by an OK button. The onClick event attribute was included for this purpose. When the Click Me button is pressed, an alert box will appear, revealing the URL of the associated page.

Uses of JavaScript Alert Method

  • To display an important message: The alert method in JavaScript is very useful to make sure that the user receives important information or confirmation before proceeding with an action. For example, we can confirm that a user has submitted a form or notify them about successful operation.
  • Input Validation Errors: It is very useful for input validation failures . With the help of alert, we can display the error messages, which will help the user to correct their mistakes. For example, when a user enters an invalid email format or if a field is left empty, which is required in those cases, it becomes very useful.
  • Useful in Debugging : Sometimes, the developers make use of alert to inspect variable values or confirm code execution flow during the development and debugging procedure.
  • Providing information to the user: It is useful to provide immediate feedback to the user. For example, confirming a password change or indicating that an item has been added to a cart, etc.
  • Conclusion

The alert method represents a fundamental concept within JavaScript. It is a native method associated with the window object, proving to be quite beneficial in a variety of scenarios. For instance, it can be utilized for Input Validation Errors, Debugging and Testing, as well as for communicating essential information. This article comprehensively discusses the JavaScript alert function and addresses several commonly asked questions. Regardless of whether you are just starting out or are a seasoned developer, this guide will enhance your understanding of this significant aspect of JavaScript.

The alert method in JavaScript serves the function of displaying a dialog box that contains a specified message along with an OK button. This is primarily utilized for notifying users about certain information or alerts in a straightforward manner. When invoked, the alert box halts the execution of the script until the user acknowledges the message by clicking the OK button. This method is particularly useful for debugging purposes or for conveying important notifications that require user attention before proceeding.

In JavaScript, the alert function is utilized to display a modal dialog box that presents a specific message along with an OK button. This feature is particularly beneficial when it is necessary to convey information to the user.

  1. In JavaScript, how many varieties of alerts exist?

There are three types of alerts in JavaScript. They are as follows:

  • Alert box: It is a pop-up box that is utilised to show some vital information or notifications to the user. It is a modal window. A user cannot interact with the page until they acknowledge it by clicking the OK button.
  • Confirm Box: In JavaScript, the confirm box is a dialog window that is utilised to get the user's confirmation for an action. It shows a message to the user with two buttons: OK and Cancel.
  • Prompt Box: In JavaScript, the prompt box is utilised to show a message to the user and give them permission to enter a value. A prompt box is created utilising the prompt method of the window object.
  1. Is alert a built-in method?

Indeed, alert is a native function within JavaScript. It allows developers to display a dialog box on the user's screen, serving to notify them about a particular event. The alert method proves to be quite beneficial for conveying information to the user, as it presents both a message and an OK button within the dialog box.

  1. Is the alert method synchronous or asynchronous?

In JavaScript, the alert function operates synchronously. When an alert dialog appears, it halts the execution of the script and requires user interaction to proceed. The alert box will remain visible until the user clicks the OK button to dismiss it.

  1. Here are several typical scenarios where the alert method is utilized.

Some commonly used cases for alerts are given below:

  • Simple confirmation message
  • Displaying error messages
  • Indicates successful operations
  1. What happens to the interface of the user when an alert box appears?

When an alert dialog is presented in a user's interface, it temporarily halts the user's ability to interact with the remaining elements of the web page until the alert box is closed by the user clicking the OK button.

Input Required

This code uses input(). Please provide values below: