Query String //JavaScript Repository

Description

Generates an associative array with the fields of the query string and its values.
Created: 2005.09.09

Code (Download)

//+ Carlos R. L. Rodrigues
//@ http://jsfromhell.com/geral/query [rev. #1]

function Query(s){
    if(!(s = s || location.search)) return null;
    var v, f, i, a = {}, r = /\+/g, u = unescape;
    if(s = s.split("?")[1])
        for(i = (s = s.split("&")).length; i;)
            (v = u((f = s[--i].split("="))[1].replace(r, " ")), a[f[0]] !== undefined)
            && (a[f[0]] instanceof Array ? a[f[0]] : a[f[0]] = [a[f[0]]]).push(v) || (a[f[0]] = v);
    return a;
}

Example (Example)

<script type="text/javascript">
//<![CDATA[
var params = Query();
if(params)
    for(var i in params)
        document.write(i + " = " + params[i] + "<br />");
//]]>
</script>

<form action="#" method="get" id="form">
    <fieldset>
    <legend>Query String</legend>
    <input type="text" name="nome" value="Nome UM" /><br />
    <input type="text" name="nome" value="Nome DOIS" /><br />
    <input type="text" name="nome" value="Nome TRES" /><br />
    <input type="text" name="nome" value="Nome QUATRO" /><br />
    <input type="radio" name="radio" value="Radio 1" />
    <input type="radio" name="radio" value="Radio 2" />
    <input type="radio" name="radio" value="Radio 3" />
    <input type="radio" name="radio" value="Radio 4" /><br />
    <input type="checkbox" name="check" value="Check 1" />
    <input type="checkbox" name="check" value="Check 2" />
    <input type="checkbox" name="check" value="Check 3" />
    <input type="checkbox" name="check" value="Check 4" /><br />
    <input type="Submit" name="sub" />
    </fieldset>
</form>

Help

Query([href: String = CURRENT_URL]): Object
Returns an associative array, where the keys are the field names of the query string. If there's more than one field with the same name, you can access it as if it was an array.
href
URL that will be parsed, the default value is the current url

Rank (Votes: 39)

2.85