1

i want to read the query string value from this anchor tag by jquery.

<td><a href="#?acckey={{user.key()}}" class="generate_url">Get URL</a></td>

this is what i wrote and it is not working

$('.generate_url').each(function () {
    $(this).click(function () {
        alert(acckey)

    });

});

but this is not working. any one know to fix this issue?

Evlikosh Dawark
  • 610
  • 2
  • 11
  • 24

3 Answers3

2
$('.generate_url').on('click', function() {
    var m = this.href.match(/acckey=(.*)/),
    acckey = m ? m[1] : '';

    alert(acckey);
});

It matches the href value against a regular expression and uses the first memory group. The acckey will be set to empty string if no match was found.

Update

To get the whole match (i.e. "acckey=xxx"), you would need to use m[0] instead of m[1].

Btw, I've removed the .each() because you were only adding a click handler.

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
2

Based on the parsing function from here, we can make the universal solution:

function getParameterByName(query_string, name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(query_string);
    if (results == null) return "";
    else return decodeURIComponent(results[1].replace(/\+/g, " "));
}

$(".generate_url").click(function() {
    var query_string = this.href.substring(this.href.indexOf("?"));
    var acckey = getParameterByName(query_string, "acckey");
    alert(acckey);
});​

DEMO: http://jsfiddle.net/dQ8Z9/


To get query string you can simply use this:

$(".generate_url").click(function() {
    var query_string = this.href.substring(this.href.indexOf("?") + 1);
    alert(query_string);
});​

DEMO: http://jsfiddle.net/dQ8Z9/1/

Community
  • 1
  • 1
VisioN
  • 143,310
  • 32
  • 282
  • 281
1
$('.generate_url').each(function () {
    $(this).click(function () {
        alert($(this).attr('href').replace(/^.*?\?/, ""));  
        /* return: acckey={{user.key()}} */
    });
});

example fiddle: http://jsfiddle.net/f4vN7/

Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177