Created
November 19, 2014 11:46
-
-
Save pulges/5c16b97041f21f7115d0 to your computer and use it in GitHub Desktop.
Autofill forms from url query
This file contains hidden or 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() { | |
// These are the form fileds you want to fill | |
// All You have to do is define the classname of the field and url parameter you want to fill, it with | |
var formFields = [ | |
{ className: "field1", parameter: "value1" }, | |
{ className: "field2", parameter: "value2" }, | |
{ className: "field3", parameter: "value3" } | |
]; | |
var field; | |
// Here an object is created containing all available parameters from url string | |
var queryString = function () { | |
var query_string = {}, | |
query = window.location.search.substring(1), | |
vars = query.split("&"), | |
arr, pair; | |
for (var i = 0; i < vars.length; i++) { | |
pair = vars[i].split("="); | |
if (typeof query_string[pair[0]] === "undefined") { | |
query_string[pair[0]] = pair[1]; | |
} else if (typeof query_string[pair[0]] === "string") { | |
arr = [query_string[pair[0]], pair[1]]; | |
query_string[pair[0]] = arr; | |
} else { | |
query_string[pair[0]].push(pair[1]); | |
} | |
} | |
return query_string; | |
}(); | |
// Loops through formFields and checks if element with className exists and if parameter exists in queryString | |
for (var f = 0, max = formFields.length; f < max; f++) { | |
field = document.querySelector("." + formFields[f].className + " input, ." + formFields[f].className + ' textarea'); | |
if (field && typeof queryString[formFields[f].parameter] !== "undefined") { | |
field.value = decodeURIComponent(queryString[formFields[f].parameter]); | |
} | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment