JavaScript: Parsing URL parameters
Submitted by dziemecki on Thu, 06/03/2010 - 14:09
Here's a nifty little JavaScript function that will read the URL of the the current page and return the value of a requested parameter:
// return a parameter value from the current URL
function getParam ( sname )
{
var params = location.search.substr(location.search.indexOf("?")+1);
var sval = "";
params = params.split("&");
// split param and value into individual pieces
for (var i=0; i<params.length; i++)
{
temp = params[i].split("=");
if ( [temp[0]] == sname ) { sval = temp[1]; }
}
return sval;
}
function getParam ( sname )
{
var params = location.search.substr(location.search.indexOf("?")+1);
var sval = "";
params = params.split("&");
// split param and value into individual pieces
for (var i=0; i<params.length; i++)
{
temp = params[i].split("=");
if ( [temp[0]] == sname ) { sval = temp[1]; }
}
return sval;
}
Given a URL something like "http://www.yoursite.com/app.asp?somevar=someval", you would call it like this:
function foo()
{
var bar = getParam("somevar");
alert(bar);
}
{
var bar = getParam("somevar");
alert(bar);
}
Tags:
Comments
Works fine! Thanks!
Works fine! Thanks!
Thanks dear...u r really
Thanks dear...u r really genious...
Nice!
Does the trick very neatly!
This doesn't handle when a
This doesn't handle when a query string doesn't have a value, it should then return `null`. It also doesn't handle `+` which means space.
See: https://github.com/sindresorhus/query-string
Thanks
Thanks................
:)
Printing the variable in an HTML Form
So how would I go about printing the variable in an HTML form field as in this example:
DOM
You'd use the Document Object Model. Something like this:
oFormObject = document.forms['myform_id'];
oFormObject.elements["element_name"].value = getParam("somevar");
http://www.javascript-coder.com/javascript-form/javascript-form-value.phtml
Dan Ziemecki
writing var values to form input values
Dan,
REAlly new to javascript.
I see this code of yours above:
Would you actually need to write two functions?
How would I get the value of ' bar ' into the input value of a field in a form?
For example here is the input line in the form:
I hope my questions are clear. %-)
Thank You,
Michelle
In reply ...
> Would you actually need to write two functions?
No. That just makes the first part reuasable. If you only need it to happen once, you can write it as one function.
> How would I get the value of ' bar ' into the input value of a field in a form?
Someone else asked about that, too. Look below at the comment titled "DOM".
Dan Ziemecki