views:

51

answers:

1

I found this snippet of code, which works a treat:

$.urlParam = function(name){
    var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (!results) { return 0; }
    return results[1] || 0;}
}

So if the url/query string was xyz.com/index.html?lang=de

just call var langval = $.urlParam('lang'); and you've got it

--

My information is coming from clicking on an image, so I created this code:

$('#admin-slideshow img').click(function() {
    alert($(this).attr('src'));
}

So if the code was:

<a href="#"><img src="image.php?url=image.jpg&tid=1&opn=1" /></a> 

it would alert just that (image.php?url=image.jpg&tid=1&opn=1).

My brainiac thought was to add that snippet of code $(this).attr('src'); and replace it with the window.location.href. It doesnt work. Any suggestions?

$('#admin-slideshow img').click(function() {
    $.urlParam = function(name){
        var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec($(this).attr('src'));
        if (!results) { return 0; }
        return results[1] || 0;}
    }
}
+2  A: 

try this,

$.urlParam = function(name, src){
    var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec( src || window.location.href); // if src is undefined defualt is window.location.href
    if (!results) { return 0; }
    return results[1] || 0;
}

use it as

$.urlParam('lang',window.location.href); // for url or just $.urlParam('lang');
$.urlParam('lang',$('#admin-slideshow img').attr('src')); // for images

$('#admin-slideshow img').click(function() {
    alert($.urlParam('opn',this.src));
}
Reigel
+1 spot on, was just typing this myself :)
karim79
You should swap `src` and `name` in the function signature: `function(name, src)`, because if `src` is the first parameter, it will **always** be defined. `$.urlParam('lang')` would have `lang` as source and `name` would be undefined.
Felix Kling
good point. thanks Felix.
Reigel
Thank-you. I have put alerts throughout the script, to see where it's erroring, and its just not passing anything... I don't know why it wouldn't work.
Phillip L
please see this [demo](http://jsfiddle.net/enz38/) and try again.
Reigel
thanks Reigel, I have updated http://jsfiddle.net/XdDXN/ with the div's and stuff I use, and your script works there, (alert wise), but it will not work on my website... this has my head going in a spin.. I will keep looking -- do you mind if you leave that up for a few days?
Phillip L
Thank-you so much for your help -- After all that it was a rouge closing bracket which wasn't allowing my script to work! Again, thank-you so much... now to incorporate mysql :( haha
Phillip L