0

Im trying to extract the value of a single $_GET variable contained in a link.

So the html looks like:

<div class="news_item"><a href="http://example.com/?p=51">Title</a></div>

And I am trying to pull out just '51' from this url using JS:

<script>
        function GetURLParameter(sParam, URL) {
            var sURLVariables = URL.split('&');
            for (var i = 0; i < sURLVariables.length; i++) 
            {
                var sParameterName = sURLVariables[i].split('=');
                if (sParameterName[0] == sParam) 
                {
                    return sParameterName[1];
                }
            }
         };

        $('.news_item a').click(function(e) {
            e.preventDefault();
            var URL = $(this).val('href');
            var sParam = 'p';
            var ID = GetURLParameter(sParam, URL);
            alert(ID);
        });


    </script>

When I click on the link I get the following error: Uncaught TypeError: Object [object Object] has no method 'split' Any ideas what is happening? I can't figure out what I have done wrong..

Thomas
  • 5,030
  • 20
  • 67
  • 100

4 Answers4

0

I think $(this).attr('href') will solve your problem however consider something like:

 var params = [];
 $(this).attr('href').replace(/[?&]+([^=&]+)=([^&]*)/gi, function(match, key, value) {
    params[key] = value;
 });

 if (params.Something) {
     // ... it's set.
 }
Martin
  • 6,632
  • 4
  • 25
  • 28
0

Try - http://jsfiddle.net/6W4Rw/

$("a").on("click", function(e) {
    e.preventDefault();
    alert( $(this).attr("href").split("=")[1] );
});
Zoltan Toth
  • 46,981
  • 12
  • 120
  • 134
0

Can you use PHP? If so it is as simple as

<script>
 var val = "<?php print $_GET['p']; ?>
</script>
chadpeppers
  • 2,057
  • 1
  • 20
  • 27
0

Plenty of answers telling you to use attr instead of val -- the return value is still undefined because you have not split your string sufficiently to have just the query arguments. You end up checking if "p" === "http://example.com/?p".

Don't forget to split off the non-query portion of the url.

cjc343
  • 3,735
  • 1
  • 29
  • 34