Udara Navarathna
Udara Navarathna

Reputation: 105

Displaying error messages without using alert in javascript/html

i'm trying to display a validation error message without using an alert box. But its not working. Previously I've used "innerHTML" successfully. But i don't understand why it doesn't work here. This is my code.

function validate()
{
  if(document.regform.fname.value.length=="")
    {
       document.getElementById("error").innerHTML="error";
    }    
}
<header>
   <h1>SIGN UP</h1>
</header>
<div class="div1"><img src="img.jpg" width="250px"></div>
<div class="div2" id="div2">
  <form name="regform" onsubmit="return validate()">
     <label><input type="text" name="fName" id="fna"></label>
     <input type="submit" name="submit" value="Sign Up" >
     <p id="error"></p>
  </form>
</div>

<footer></footer>

Upvotes: 1

Views: 10849

Answers (1)

Anup Kumar Gupta
Anup Kumar Gupta

Reputation: 361

There are some mistakes in your code. Firstly the name is fName but you are using fname and then you must compare length by an integer value not empty string.

Also you would like to stop the submission if an error occurred. Hence you return a false if there is an error. Try this.

function validate() {
  if (document.regform.fName.value.length == '0') {
    document.getElementById("error").innerHTML = "error";
    return false;
  }
}
<body>
  <header>
    <h1>SIGN UP</h1>
  </header>
  <div class="div2" id="div2">
    <form name="regform" onsubmit="return validate()">

      <label><input type="text" name="fName" id="fna"></label>
      <input type="submit" name="submit" value="Sign Up">
      <p id="error"></p>
    </form>
  </div>
  <footer></footer>
</body>

Hope it works.

Upvotes: 1

Related Questions