views:

25

answers:

2

I can do this

jQuery.fn.validate = function(options) {
    var defaults = {
        validateOPtions1 : '',
        validateOPtions2 : ''
    };

    var settings = $.extend({}, defaults, options);

    return this.each(function() {
        // you validation code goes here
    });
};

but that will make validate() available for every element. I could do this to any element: $('some selector').validate().

Is there a way I can make this only available to, say, form elements? eg. $('.mySpecialFormClass').validate()?

+1  A: 

The answer is simple:

$('form').validate();

Selectors work a bit like this in jQuery (just as in CSS)

$('elementType.className')

See this page for more details on selectors.

Aaron
I want to make it so that .validate() is unavailable to anything except elements of type 'form'. So, if I called, $('div').validate(), an 'undefined function' should would be thrown. For instance, .val() (I believe) only works with form element (input, select, textarea).
Chad Johnson
@Chad that's not the case - you can use `val()` with anything you want. It won't *work*, of course, but the framework doesn't make it impossible to even call it.
Pointy
Yeah, I just realized that.
Chad Johnson
In that case, I agree with Pointy's answer.
Aaron
+2  A: 

You'd have to have the function throw an exception if you really don't want it to work for anything but a <form> tag.

jQuery.fn.formsOnly = function() {
  return this.each(function() {
    if (!$(this).is('form')) throw "Forms only!";
    // whatever
  });
};
Pointy