How do I add a function to an element via jQuery?

Posted by Chad Johnson on Stack Overflow See other posts from Stack Overflow or by Chad Johnson
Published on 2010-04-14T19:44:32Z Indexed on 2010/04/14 19:53 UTC
Read the original article Hit count: 190

Filed under:
|

I want to do something like this:

$('.dynamicHtmlForm').validate = function() {
  return true;
}

$('.dynamicHtmlForm .saveButton').click(function() {
  if (!$(this).closest('.dynamicHtmlForm').validate()) {
    return false;
  }

  return true;
});

And then when I have a form of class dynamicHtmlForm, I want to be able to provide a custom validate() function:

$('#myDynamicHtmlForm').validate = function() {
  // do some validation

  if (there are errors) {
    return false;
  }

  return true;
}

But I get this when I do this:

$(this).closest(".dynamicHtmlForm").validate is not a function

Is what I've described even possible? If so, what am I doing wrong?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery