How to display errors without an alert box using JavaScript?

Here we will learn how to display errors inline on a page and without an alert box using javascript with the help of innerHTML and textContent properties of HTML DOM elements.

While alert boxes can be useful for displaying errors to users, they can be disruptive and interrupt the user experience. A more elegant solution is to display errors inline on the page.

Let’s understand how to achieve the above result :

Approach

In this approach, we will use the innerHTML DOM element property to display the error message inline in a form.

Example

Let’s understand the above approach with the help of an example.

Filename: index.html

<html lang="en">
<head>
   <title>How to display error without alert box using JavaScript?</title>
   <style>
      span {
         color: red;
      }
   </style>
</head>
<body>
   <h3>How to display error without alert box using JavaScript?</h3>
   <form name="myForm" onsubmit="return validateForm()">
      <label for="name">Name:</label>
      <input type="text" id="name" name="name"><br>
      <span id="nameError"></span><br>
      <input type="submit" value="Submit">
   </form>

   <script>
      function validateForm() {
         var name = document.forms["myForm"]["name"].value;
         if (name == "") {
            document.getElementById("nameError").innerHTML = "Please enter your name";
            return false;
         }
      }
   </script>
</body>
</html>

Conclusion

By displaying errors inline on the page instead of using alert boxes, one can provide a more elegant and user-friendly experience for their users.

Related Posts

What are custom events in JavaScript?

Custom events are the events that allow you to decouple the code you want to run after a specific piece of code runs. There are various in-built events…

How to use nested for loop in JavaScript?

We use the for loop statement of JavaScript for repeating a set of statements inside the loop body a specified number of times. A nested for loop, as the…

What are the basic rules for JavaScript parameters?

A JavaScript function is a code that performs a particular task. The function parameters are the name list in the function definition. Parameters are also known as…

How to stop refreshing the page on submit in JavaScript?

Using event.preventDefault() to stop page refresh on form submit In this section, we will see how to use event.preventDefault() to stop page refresh on form submission. The event.preventDefault() restricts the default…

Target a Window Using JavaScript or HTML

TARGET attribute of HTML A link’s opening named frame or window is specified using the Target attribute of the <a> anchor tag. The concluding </a> tag in…

What is the role of deferred scripts in JavaScript?

Since JavaScript is a loosely typed language, you are not required to correctly predict the kind of data that will be kept in a variable. Depending on the information…