How to add a function to an element through 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 the dynamicHtmlForm class, I want to be able to provide a validate () custom 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 this what I described is even possible? If so, what am I doing wrong?

+6
javascript jquery
source share
3 answers
 jQuery.fn.validate = function(options) { var defaults = { validateOPtions1 : '', validateOPtions2 : '' }; var settings = $.extend({}, defaults, options); return this.each(function() { // you validation code goes here }); }; $(document).ready(function() { $('selector').click(function() { $('some selector').validate(); // or if you used any options in your code that you // want the user to enter. then you go : $('some selector').validate({ validateOPtions1: 'value1', validateOPtions2: 'value2' }); }); }); 
+3
source share

Yes, it is technically possible. However, you will need to reference the element itself, 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; } 
+5
source share

You are not adding a function to the element, you are adding it to the jQuery wrapper around the element. Each time you pass a selector to jQuery, it will create a new wrapper for the elements found:

 $('#myEl'); // gives a jQuery wrapper object $('#myEl'); // creates another jQuery wrapper object 

If you save the wrapped element into a variable and use it later, it will be a different story because you are accessing the saved jQuery wrapper object.

 var dynamicHtmlForm = $('.dynamicHtmlForm'); dynamicHtmlForm.validate = function() { return true; } $('.dynamicHtmlForm .saveButton').click(function() { if (dynamicHtmlForm.validate()) { return false; } return true; } 

You can also add a function directly to an element using

 $('.dynamicHtmlForm')[0].validate = function () { return true; } // and later... if (!$(this).closest('.dynamicHtmlForm')[0].validate()) 

Or you can look at the jQuery extension correctly spelling the plugin .

+3
source share

All Articles