Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 201
Chad Johnson Avatar asked Apr 14 '10 19:04

Chad Johnson


People also ask

How do you create a function in jQuery?

Answer: Use the syntax $. fn. myFunction=function(){} The syntax for defining a function in jQuery is little bit different from the JavaScript.

Can we call function in jQuery?

Calling a JavaScript library function is quite easy. You need to use the script tag. As almost everything we do when using jQuery reads or manipulates the document object model (DOM), we need to make sure that we start adding events etc. as soon as the DOM is ready.

What is ADD method in jQuery?

jQuery add() Method The add() method adds elements to an existing group of elements. This method adds elements on the whole document, or just inside context elements if the context parameter is specified.

What is $( function in jQuery?

Specifies a selector expression, element or a jQuery object to match the current set of elements against. Returns true if there is at least one match from the given argument, and false if not.


1 Answers

Yes, it is technically possible. You will need to reference the element itself, however, and not the jQuery collection. This should work:

$('.dynamicHtmlForm').each(function (ix,o) {
  o.validate = function() {
    return true;
  }
});

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

  return true;
}
like image 138
Dereleased Avatar answered Sep 28 '22 17:09

Dereleased