Skip to content

Instantly share code, notes, and snippets.

@schie
Created September 28, 2017 18:33
Show Gist options
  • Save schie/74d800aeaa72901370dbde640bb82b41 to your computer and use it in GitHub Desktop.
Save schie/74d800aeaa72901370dbde640bb82b41 to your computer and use it in GitHub Desktop.
Setting form fields with query string
function parseSearchString () {
var qs = window.location.search
qs = qs.replace(/^\?/,'')
var parts = qs.split('&')
var params = {}
parts.forEach(function (part) {
var pair = part.split('=')
params[pair[0]] = decodeURIComponent(pair[1])
})
return params
}
window.onload = function () {
var qs = parseSearchString()
Object.keys(qs).forEach(function (key) {
var elByName = document.querySelectorAll('[name=' + key + ']');
var elByID = document.querySelectorAll('#' + key);
// first try to set element value with provided name
if (elByName.length) {
elByName[0].value = qs[key];
}
// otherwise, try to set element value by id
else if (elByID.length) {
elByID[0].value = qs[key];
}
// .. more things
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment