soum soum - 1 year ago 66
jQuery Question

Not able to call a method by using 'this' keyword inside another method from a same class

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"/>

And the JS is

var Form = function(){};

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

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


Form.prototype.test = function(){
var form = new Form();

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?

Answer Source

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){
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download