user829174
user829174

Reputation: 6362

JS how to take parameter name from URL

I am currently in a page that its url is http://localhost:49852/Default.aspx?MID=17

in this page i have the following code

<a href="Configure.aspx"><span class="ico gray shadow gear"></span>Configure</a>

I would like that once the user will click on Configure link the MID parameter from the URL will be cropped and the user will be redirected to

http://localhost:49852/Configure.aspx?MID=17

This is the JS Code

function getParameterByName(name) {
    var match = RegExp('[?&]' + name + '=([^&]*)')
            .exec(window.location.search);
    return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}

How do i bind it all together?

Upvotes: 0

Views: 78

Answers (3)

You can parse the MID from QueryString with this nice function as explained at Parse query string in JavaScript and build a new URL with it.

function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split('&');
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split('=');
        if (decodeURIComponent(pair[0]) == variable) {
            return decodeURIComponent(pair[1]);
        }
    }
    console.log('Query variable %s not found', variable);
}

like ;

var mid = getQueryVariable(MID);
var url = 'http://localhost:49852/Configure.aspx?MID='+mid;
location.href=url;

Upvotes: 0

Christofer Eliasson
Christofer Eliasson

Reputation: 33865

You could attach a click-event listener on the element, and when clicked, you modify window.location to perform the redirect. Something like this:

$(function () {
   // You might need to use a better selector here, 
   // add an ID to the span element and select on that instead
   $("span.ico").on("click", function () {
      window.location.href = "Configure.aspx?MID=" + getParameterByName("MID");
      return false;
   });
});

Upvotes: 0

Joel Etherton
Joel Etherton

Reputation: 37533

First I think you should give your href an id for easy access like:

<a href="Configure.aspx" id="configure"><span class="ico gray shadow gear"></span>Configure</a>

Then you should be able to change the property with:

$(function() {
    var href = $("#configure").attr("href");
    $("#configure").attr("href", href + getParameterByName("MID"))
});

This will change the actual href. You could probably just as easily override the click method, but this might be more extensible if you want to change it from the configure link to all links or something.

Upvotes: 3

Related Questions