0

I was trying to make a registration form using HTML, Bootstrap and JavaScript. I am able to get the error message when a field is left empty, but the error message vanishes just after showing up. I don't know what am I doing wrong

function checkValidation() {
    var firstName = document.getElementById('firstName').value;
    if (firstName == "") {
        console.log("enter");
        document.getElementById('firstNameErrorMessage').innerHTML = "please enter";
    } else {
        console.log("done");
    }
}
<div class="container-fluid">
  <div class="container">
    <h2>Registration Form</h2>
    <form class="form-horizontal" name="myForm">
      <div class="form-group">
        <label class="control-label col-sm-2" for="firstName">
        First Name
        </label>
        <div class="col-sm-10">
          <input type="text" name="firstName" class="form-control" id="firstName" placeholder="Enter your First Name" name="firstName">
          <div class="col-sm-12">
            <p id="firstNameErrorMessage"></p>
          </div>
        </div>
      </div>
      <div class="form-group">
        <div class="col-sm-offset-2 col-sm-10">
          <button type="submit" class="btn btn-default" onclick="checkValidation()">Submit</button>
        </div>
      </div>
    </form>
  </div>
</div>
pratteek shaurya
  • 850
  • 2
  • 12
  • 34

1 Answers1

1

You will need to use preventDefault in order to make it work as intended:

<div class="container-fluid">
<div class="container">
<h2>Registration Form</h2>
<form class="form-horizontal" name="myForm">
  <div class="form-group">
    <label class="control-label col-sm-2" for="firstName">
    First Name
    </label>
    <div class="col-sm-10">
      <input type="text" name="firstName" class="form-control" id="firstName" placeholder="Enter your First Name" name="firstName">
      <div class="col-sm-12">
        <p id="firstNameErrorMessage"></p>
      </div>
    </div>
  </div>
  <div class="form-group">
    <div class="col-sm-offset-2 col-sm-10">
      <button type="submit" class="btn btn-default" onclick="checkValidation(event)">Submit</button>
    </div>
  </div>
</form>

and

function checkValidation(e) {
e.preventDefault();
var firstName = document.getElementById('firstName').value;
if (firstName == "") {
    console.log("enter");
    document.getElementById('firstNameErrorMessage').innerHTML = "please enter";
} else {
    console.log("done");
  }
 }

Have a look here for some preventDefault questions:

How and when to use preventDefault()?

What's the difference between event.stopPropagation and event.preventDefault?

monogate
  • 1,419
  • 1
  • 11
  • 16