Access variable from event handler in javascript object

event-handling, javascript, jquery, oop

Solution

`this` is not a local variable, so it doesn't get saved in closures. You need to save it in a local variable. In jQuery event handlers, `this` is always bound to the target of the event.

function DataValidator(selector)
{
  this.form = $(selector);
  this.selector = selector;
  var self = this;

  this.form.submit(function() 
  {
    alert('submit ' + self.selector);
    return false;
  });
}

Problem

I'm trying to create a jQuery class to validate input fields when a form is submitted. I have different forms into the same page and I need to create a validator instance for each form. HTML ``` <form method="post" action="index.php" id="form1"> <input type="submit" value="Send" /> </form> <form method="post" action="index.php" id="form2"> <input type="submit" value="Send" /> </form> <script type="text/javascript"> var form1 = new DataValidator('#form1'); var form2 = new DataValidator('#form2'); </script> ``` I would access object variables from submit event handler, but when I print `this.selector` variable, I see an `undefined` value. JavaScript ``` function DataValidator(selector) { this.form = $(selector); this.selector = selector; $(selector).submit(function() { alert('submit ' + this.selector); return false; }); } ```

Original source