0

I am trying to pass an alert after the user submits a form. The html is like this

<form id="profile" name="profile">
  <label for="firstName">Male</label>
  <input type="text" name="firstname" id="firstName" maxlength="20" class="required" value=""/>
  <input type="submit" name="sumit" value="submit"/>
</form>

And the JS is

var Form = function(){}; 

Form.prototype.formValidate = function($form){

    $form.on('submit', function(e){
    e.preventDefault();
    this.test()// this doesn't work
    //alert('t') // this works
  })

}

Form.prototype.test = function(){
    alert('t');
}
var form = new Form();
form.formValidate($('#profile'))

When I am getting an error saying ..this.test is not a function... If I just pass the alert right after the e.preventDefault() but it cant call I cant call a method by a keyword 'this'. Which makes me say my scope is not right. What am I missing?

soum
  • 1,063
  • 3
  • 17
  • 43

1 Answers1

3

In JavaScript, the value of this is based on scope. Every time you have function(){}, then you have a new scope. Inside each function, this is going to be different, it's set based on how that function is called.

Where you are doing this.test(), this is not the Form object, it's the #profile element. You'll need to save the this value into a variable so you can use it in the event.

Form.prototype.formValidate = function($form){
    var self = this;

    $form.on('submit', function(e){
        e.preventDefault();
        self.test();
    });
};
Rocket Hazmat
  • 204,503
  • 39
  • 283
  • 323
  • Right..I could call it just fine outside the $form.on() – soum Jun 03 '16 at 16:14
  • @soum: Exactly, because then you were inside a function on the `Form` object. Once you're inside the event, you are in a new context and `this` has changed. That's why you need to *save* it as a variable then access that variable inside the event. – Rocket Hazmat Jun 03 '16 at 16:15