JavaScript

How to show an error message beside a field in HTML using Javascript

In this tutorial, we are going to see how to display an error message beside an input in JavaScript. In the example below, we will display the error message in case the user has not completed the text input.
 

How to show an error message beside a field in HTML using Javascript
<html>
   <head>
      <script> 
         function validateForm()                                 
         { 
             var name = document.forms["myForm"]["name"];         
             if (name.value == ""){ 
                 document.getElementById('errorname').innerHTML="Please enter a valid name";  
                 name.focus(); 
                 return false; 
             }else{
                 document.getElementById('errorname').innerHTML="";  
             }
         }
      </script> 
      <style>
         .error{
            color: #D8000C;
            background-color: #FFBABA;
         }
      </style>
   </head>
   <body>
      <form name="myForm" onsubmit="return validateForm()">
         <p>Your name: <input type="text" name="name" class="field-long"/>  <span class="error" id="errorname"></span></p>
         <p><input type="submit" value="Send"></p>
      </form>
   </body>
</html>
Result

Your name:

mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *