Alex
Alex

Reputation: 35831

How to turn function into jQuery plugin

Here's my jsFiddle: http://jsfiddle.net/jsFiddlePlayer/vhg7csb7/10/

I am trying to implement the answer in this StackOverflow question as a jQuery plugin and having no luck. The getParameterByName function reads the URL's querystring variables and returns the one indicated in the argument. However, my code keeps saying:

.getParameterByName is not a function

My jQuery code is as follows:

$(document).ready(function(){
    var paramABC = $.getParameterByName('abc');    
    alert(paramABC);
});

(function ($) {
    /* Gets value of querystring variable by name */
    $.fn.getParameterByName = function (name) {
        name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
            results = regex.exec(('http://www.myexample.com/?abc=1&def=2').search);
        return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    };
}(jQuery));

Note that I've hardcoded a location in the above function because jsFiddle doesn't have querystring variables on the URL. The original code for that line was:

results = regex.exec(location.search);

If this code was working, it would return 1 (because abc=1 in the querystring) and display it in the alert(). What am I doing wrong? Thanks.

Upvotes: 0

Views: 94

Answers (2)

Satpal
Satpal

Reputation: 133403

You are almost there use $ instead of $.fn, as $.fn is an alias for the prototype of jQuery and it expects a selector

$.getParameterByName = function (name) {
   //
};

Note: Define plugin code first then use it.

A good read What is the difference between $ and $.fn?

DEMO

Upvotes: 4

RobertoNovelo
RobertoNovelo

Reputation: 3809

You are missing the selector $() since you are extending $.fn

$(document).ready(function(){
    var paramABC = $().getParameterByName('abc');    
    alert(paramABC);
});

(function ($) {
    /* Gets value of querystring variable by name */
    $.fn.getParameterByName = function (name) {
        name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
            results = regex.exec(('http://www.myexample.com/?abc=1&def=2').search);
        return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    };
}(jQuery));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 0

Related Questions