Accessing querystring value using JavaScript

When I was working with server-side script, I have the question its possible to access query-string values from JavaScript. But which way it will be identify the each parameters from the query-string.

In JavaScript we have method “window.location.href” which will read url and query-string. We will create two html file, first one will have text-box and submit, second html file will display query-string in webpage.

first.html

<table>
<form action="result.html" method="get">
<tr>
<td>Name</td>
<td><input type="text" name="txtName" /></td>
</tr>
<tr>
<td>Age</td>
<td><input type="text" name="txtAge" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="btnSubmit" value="Submit" /></td>
</tr>
</form>
</table>

result.html

<script>
// reading url and splitting url and parameters
var result = window.location.href.split("?");

// splitting the parameters
var r = result[1].split("&");
var arr = [];

for(k in r) {
	// splitting the parameters for name and values
	v = r[k].split("=");

	// pushing the name and value into array
	arr.push(v[0]+"_"+v[1]+"<br />");
}

// last printing the array
document.write(arr);
</script>

[ Download ] | [ Demo ]
Share