Thursday 19 February 2015

jQuery plugin to receive GET parameters and add them to an element

Below is my simple page. What I'd like to do, as you can see from the code in red is to call a jQuery plugin. The plugin find the message parameter sent to a page and apply its value to the #message div. So the call to the page would be something like this mypage.html?message=Hello+world
Then the words 'Hello world' would appear inside the div.

<!DOCTYPE html>
<html lang="en">
<head>  
<body>  
  <div class="id="message"></div>
  <script src="jquery/1.11.2/jquery.min.js"></script>
  <script src="js/receiveget.plugin.js"></script>
  <script>
  (function()
  {
    $('#message').receiveget('message');
  })();
  </script>
  </body>
</html>

So here is my receiveget.plugin.js
(function($)
{
    $.fn.extend(
    {
        receiveget:function(getvar)
        {
            var sPageURL = window.location.search.substring(1);
            var sURLVariables = sPageURL.split('&');
            for (var i = 0; i < sURLVariables.length; i++)
            {
                var sParameterName = sURLVariables[i].split('=');
                if (sParameterName[0] == getvar)
                {
                    $(this).text(decodeURIComponent(sParameterName[1].replace('+', ' ')));
                }
            }
        }
    });
})(jQuery);

No comments:

Post a Comment