DaveDev
DaveDev

Reputation: 42175

How to create a jQuery function to return a bool?

How can I create a jQuery function like

$.MyFunction(/*optional parameter*/)?

which will return a bool?

note:

I've tried this:

jQuery.fn.isValidRequest = function (options) {

    return true;
}

// I'm contending with Prototype, so I have to use this    
jQuery(document).ready(function ($) {    

    // and jQuery 1.2.6, supplied by the client - long story
    $('a').livequery('click', function () {

        alert($.isValidRequest("blah"));
        return false;
    });
});

but it crashes on the alert() with

Microsoft JScript runtime error: Object doesn't support this property or method

This is what worked in the end:

jQuery.isValidRequest = function (options) {

    return true;
}

Upvotes: 3

Views: 24684

Answers (5)

ovais.tariq
ovais.tariq

Reputation: 2625

For a function you intend to call from jQuery instances, you'd define it like this:

$.fn.MyFunction = function(options)
{
  // return bool here
};

And call like any other jQuery method:

$('selector').MyFunction(...);

A function intended to be called from the global jQuery object (or its $ alias) would be attached directly to that object:

$.MyFunction = function(options)
{
  // return bool here
};

And call the same way:

$.MyFunction(...);

Note that I've used $.fn for brevity - this can cause problems if jQuery is prevented from using the $ alias for compatibility with other libraries. The recommended way to attach a plugin function is:

(function($) // introduce scope wherein $ is sure to equate to jQuery
{ 
  $.fn.MyFunction = function(options) 
  { 
    // return bool here 
  };
})(jQuery); // conclude plugin scope

Note also that most jQuery functions return this, to enable chaining; if you opt to return some other value, you'll be unable to do this. Be sure to document clearly that your function returns a boolean, or you'll find yourself wondering why e.g. $("...").MyFunction().hide() breaks later on.

You can read more about extending jQuery here:
Extending jQuery – plugin development
and in the jQuery documentation:
Plugins/Authoring

Upvotes: 6

Ian Henry
Ian Henry

Reputation: 22403

$.fn.MyFunction = function(param) {
   if(arguments.length > 0)
      return true;
   else
      return false;
}

Upvotes: 1

John Strickler
John Strickler

Reputation: 25421

$.fn.MyFunction = function(params) { return true; }

Upvotes: 0

pixeline
pixeline

Reputation: 17974

$.myfunction(options){
return options.isThisTrue;
}

usage:

       $(document).ready(function(){ 
         var isThisTrue = $.myfunction({isthisTrue: false});
         // isThisTrue is false
        });

Upvotes: 0

Lloyd
Lloyd

Reputation: 29668

http://blogs.microsoft.co.il/blogs/basil/archive/2008/09/22/defining-your-own-functions-in-jquery.aspx

You can still just return like in plain JavaScript true/false for boolean parameters.

Upvotes: 0

Related Questions