4

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;
  });
}
1

1 Answer 1

4

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;
  });
}
Sign up to request clarification or add additional context in comments.

1 Comment

in fact this in the OP's code is just the form object, not the object created by DataValidator constructor.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.