I have a very simple form on my site http://www.example.com
<form>
<input type="text" value="" name="name">
</form>
How do I get my form to look like this
<form>
<input type="text" value="tom" name="name">
</form>
If I type in (or a user is taken to this page from a search page) http://www.example.com?name=tom
bearing in mind at some point my form may look like this.
<form>
<input type="text" value="" name="name[]">
<input type="text" value="" name="name[]">
<input type="text" value="" name="name[]">
<input type="text" value="" name="name[]">
</form>
so I would like to handle an array of names as well. I have had a look at jQuery.param() but can’t get my head around how I would do this. Is it possible without submitting to a server side language sucha as php?
There’s no baked-in jQuery way to get name/value pairs from the querysting to javascript variables (though, shouldn’t there be??)
But folks have written pure javascript functions to do that for you: How can I get query string values in JavaScript?.
If you use the 2nd answer to the above question, by Andy E, you can capture all the querystring vars to name-value pairs of a javascript object. Here’s what he wrote:
Then use these to set the form values of inputs with the same name as the querystring names with jQuery like this:
Update: since this is hard to test in jsFiddle, here is an entire web page as a working example. It will replace the values ‘a’, ‘b’, and ‘c’ with those passed in by the url (‘1’, ‘2’, and ‘3’) — just set this up as test.html on localhost and go to:
http://localhost/test.html?a=1&b=2&c=3