1

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()?

2 Answers 2

2

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

Comments

1

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.

3 Comments

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 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.
In that case, I agree with Pointy's answer.

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.