Jake P Fill form fields based on url query parameters

Created by Jake P
function fillFieldsFromParams(fieldName,paramName,formSelector) {
	var automatic = false,
		, formSelectorString = ''
		, parseQueryParameters=function(){var queryString=window.location.search,queries={};if(queryString=='') return queries;var q=queryString.replace('?','').split('&');q.forEach(function(pair,index){var a=pair.split('=');if(typeof a[1]==='undefined')a.push('');queries[a[0]]=a[1];});return queries;}
		, getQueryStringValue=function(param){if(typeof queries==='undefined'){var queries=parseQueryParameters();}if(typeof queries[param]=='undefined'){return false;} return queries[param];};
		, cleanFieldValue=function(str){var out=decodeURI(str);return out;};	

	if( 
		( typeof fieldName === 'undefined' && typeof paramName === 'undefined')
		||
		(fieldName === false && paramName === false)
	) {
		automatic = true;
	}
	else if( typeof paramName === 'undefined' || paramName === false) {
		var paramName = fieldName;
	}

	if(typeof formSelector == 'string'){
		formSelectorString = formSelector + ' ';
	}

	if( automatic ) {
		var params = parseQueryParameters();
		for( paramValue in params ){
			if( ! params.hasOwnProperty(paramValue) ) continue;
			var field = document.querySelectorAll(formSelectorString+'input[name="'+paramValue+'"]');
			if( field ){
				for(var i=0;i<field.length;i++)
					field[i].value = cleanFieldValue(params[paramValue]);
			}
		}
	} else {
		var v = getQueryStringValue(paramName);
		var field = document.querySelectorAll(formSelectorString+'input[name="'+fieldName+'"]');
		if( v && field ){
			for(var i=0;i<field.length;i++)
				field[i].value = cleanFieldValue(v);
		}
	}
}

Comments (0)