LifeStartsAtHelloWorld
LifeStartsAtHelloWorld

Reputation: 979

Event not getting called from submit button Javascript

I am new to javascript. I am trying to figure out why my javascript function is not being called. I am trying to add nameVlidation for name field and other validation for each text input. But my name validation itself is not working.

Javascript call (formValidation.js)

'use strict';

var nameValidation = formValidation().nameValidation();

document.getElementById('submit').addEventListener('click',nameValidation);

var formValidation = function () {

return {
    nameValidation: function() {

        this.name = document.forms["contact"]["name"].value;

        if(this.name=="") {
            alert("Enter name, required");
            return false;
        }else if(this.name==[0-9]) {
            alert("Only alphabets");
        }

        return true;
    },

    addressValidation: function() {

    }
  }
};

Html

    <form name="contact" action="#" method="post" enctype="text/plain">
<input type="text" name="name" placeholder="NAME"></br>
<input type="text" name="email" placeholder="EMAIL" required></br>
<input type="text" name="phoneNumber" placeholder="PHONE-NUMBER"></br> 
 <input type="text-box" name="message" placeholder="MESSAGE"></br>
<button id="submit" class="btn btn-primary" type="submit"><i class="fa fa-paper-plane">Submit</i></button></br>
  </form>
<script src="js/formValidation/formValidation.js"></script>

I am not sure what is wrong with it.

Upvotes: 0

Views: 45

Answers (2)

Sahan Serasinghe
Sahan Serasinghe

Reputation: 1651

The problem you are facing is due to a concept in Javascript called, Hoisting

You need to declare formValidation at the top before calling it from anywhere else, as you are using the function expression form

'use strict';

var formValidation = function () {

return {
    nameValidation: function() {

        this.name = document.forms["contact"]["name"].value;

        if(this.name=="") {
            alert("Enter name, required");
            return false;
        }else if(this.name==[0-9]) {
            alert("Only alphabets");
        }

        return true;
    },

    addressValidation: function() {

    }
  }
};

var nameValidation = formValidation().nameValidation();

document.getElementById('submit').addEventListener('click',nameValidation);

PS - JSBin Demo

Upvotes: 0

Hameed Syed
Hameed Syed

Reputation: 4245

     'use strict';
//Rest of your code goes here
        document.getElementById('submit').addEventListener('click',nameValidation);

Because of function hoisting in Javscript.By default, JavaScript moves all the function declarations to the top of the current scope. This is called function hoisting. This is the reason your nameValidation function is not called in your current code.

Upvotes: 1

Related Questions