Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pre-populate html form input fields from url parameters?

Tags:

I have a vanilla html page which has a form in it. A requirement has come in to be able to pre-populate the form via the url. Something like:

http://some.site.com/somePage.html?forename=Bob&surname=Jones 

I can't seem to find any simple solution to this. Can someone point me in the right direction with some javascript to accomplish this? Happy to use a javascript solution, but I'd prefer to avoid pulling in an entire library just for this single use (none are currently used). Thanks.

like image 468
Chris Knight Avatar asked Mar 24 '11 16:03

Chris Knight


People also ask

What can be used to automatically populate fields in a form?

You can auto-populate form fields on a page by adding query strings to the page URL before sending it to your contacts. Fields will populate based on the query string added.


2 Answers

Use a custom query string Javascript function.

function querySt(ji) {      hu = window.location.search.substring(1);     gy = hu.split("&");      for (i=0;i<gy.length;i++) {         ft = gy[i].split("=");         if (ft[0] == ji) {             return ft[1];         }     } } var koko = querySt("koko"); 

Then assign the retrieved value to the input control; something like:

document.getElementById('mytxt').value = koko; 
like image 158
Ian Avatar answered Nov 12 '22 13:11

Ian


Are you using PHP? If so, that makes things much easier. Assuming your link as above, you can use:

<?php $forename = $_GET['forename']; $surname = $_GET['surname']; ?> ---------- <input id='forename' type='text' value='<?php echo $forename; ?>' > <input id='surname' type='text' value='<?php echo $surname; ?>' > 

That should pre-populate for you.

like image 37
paradox870 Avatar answered Nov 12 '22 13:11

paradox870