Calculated Fields Form – Populating a field with an parameter of the URL

Sometimes is desired populate a field in the form with the value of a parameter received through the URL, to create a more dynamic forms. In this case will be needed to include some javascript code in the page for extracting the value of the URL parameter, and then get the field on page, and populate it with the value of the parameter.

content-editor

Fig. 1 Content Editor

Before inserting the code in your page, you should activate the “Text” tab in the editor (fig. 1), because in the “visual” tab the symbols “<“, and “>” are converted to “&lt;” and “&gt;” respectively.

I’ll try to explain the process through an example. I want get the parameter “email” from the URL, and assign its value to the field: fieldname3 in the form (the parameter’s name and the name of fields are selected randomly)

The parameter is extracted from the URL through the following function:

function urlParam(name)
{
var results = new RegExp(‘[\?&]’ + name + ‘=([^&#]*)’).exec(window.location.href);
return ( results ) ? decodeURI(results[1]) : ”;
}

So, if you want get the value of the “email” parameter in the URL, you simply should call the “urlParam” function, with the “email” text as the function’s parameter:

urlParam(“email”);

To access to the “fieldname3? field in the webpage using jQuery, the code used would be:

jQuery(“#fieldname3_1”)

The field’s name is fieldname3 but should be used fieldname3_1, because the plugin adds the string “_#”, to the IDs of the fields, where the symbol “#” identifies the instance of the form, to prevent conflicts with the fields names, for example the fields in the first form on page, are completed with the “_1” text, the fields in the second form with the “_2” text, and so on.

Our plugin calls the event “showHideDepEvent” when the form has been generated and displayed, so the field should be populated in the first launch of this event, and then, call the “change” event, after populate the field to be sure the equations that depend of this field are evaluated.

jQuery( document ).one( “showHideDepEvent”, function(){ jQuery( “#fieldname3_1” ).val( urlParam( “email” ) ).change(); } );

The final code would be:

<script>
function urlParam(name)
{
var results = new RegExp(‘[\?&]’ + name + ‘=([^&#]*)’).exec(window.location.href);
return ( results ) ? decodeURI(results[1]) : ”;
}

jQuery(function(){
jQuery( document ).one( “showHideDepEvent”, function(){ jQuery( “#fieldname3_1” ).val( urlParam( “email” ) ).change(); } );
});
</script>

http://wordpress.dwbooster.com/forms/calculated-fields-form