Reputation: 35831
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
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?
Upvotes: 4
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