Created
September 28, 2017 18:33
-
-
Save schie/74d800aeaa72901370dbde640bb82b41 to your computer and use it in GitHub Desktop.
Setting form fields with query string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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