views:

36

answers:

1

Hello there,

Markup:

<input type="text" name="email" />

Code:

$(':text').focusout(function(){
    $(this).validate(function(){
        $(this).attr('name');
    });
});

Plugin:

(function($){  
    $.fn.validate = function(type) {  
        return this.each(function(type) {  
            if (type == 'email') {
                matches = this.val().match('/.+@.+\..{2,7}/');
                (matches != null) ? alert('valid') : alert('invalid');
            }
            /*else if (type == 'name') {

            }
            else if (type == 'age') {

            }
            else if (type == 'text') {

            }*/
            else {
                alert('total failure');
            }
        });
    };  
})(jQuery);

The problem is that when I execute the code above, it runs the plugin as if type was a string: "function(){ $(this).attr('name'); });" instead of executing it as a function. How do I solve this?

Thank you for your time.

Kind regards, Marius

A: 

You must check if the parameter is a function. If yes use the return value else assume it's a literal value.

(function($) {
    $.fn.validate = function(type) {
        //check if type type is a function else take it as literal
        type = typeof type !== "function" ? type : type();
        return this.each(function(type) {
            ...
        });
    };
})(jQuery);
jitter