Tuesday, September 20, 2011

JS 101: How to get URL parameters from HTML page

Same with PHP or ASP page, HTML will be able to get the query string parameters but not that as easy compare to PHP and ASP.

We can get it by parsing the URL parameters via javascript, and to help you with, I created a script below that does it.

The script will parse and get the "spage" parameter of the HTML page and prompt it via alert dialog box. Sample URL will be.. index.htm?spage=1..

var spage = getUrlParam("spage");
alert(spage);

function getUrlParam(param)
{
    var hash = [];
    var value = '';
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    

    for(var i = 0; i < hashes.length; i++) { 
        hash = hashes[i].split('='); 
        if (hash[0] == param) value = hash[1]; 
    } 

    return value;
}

Hope you like it!!

No comments:

Post a Comment