How can I pre-populate html form input fields from url parameters?
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? H开发者_JAVA技巧appy 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.
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;
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.
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
var get = getUrlVars();
//returns get['forename'] == bob; surname == jones
Here is the builtin way, for reference: https://developer.mozilla.org/en-US/docs/Web/API/URL/searchParams
You can instantiate the current address's parameters as a URL object without importing any libraries as shown here:
let params = (new URL(document.location)).searchParams;
Then you can reference them directly:
let name = params.get('name');
Or you can cycle through them with a loop such as:
for (const [key, value] of params.entries()) {}
精彩评论