How to Dynamically Populate a Field from another field in Gravity Forms (using JavaScript)
It’s sometimes useful to fill in form fields from fields higher up in the form.
In this example, we’ll show how selecting a value in a ‘drop down’ field will display a specific message in a ‘text’ field.
The form and field IDs are indicated as parameters at the beginning of the JavaScript code, which has been added to the form using the extension provided by Gravity Wiz.
gform.addFilter('gform_datepicker_options_pre_init', function(optionsObj, formId, fieldId) { // START config var formID = GFFORMID; var fieldCheck = 100; // field to check var fieldResult = 123; // field to display result // END config if (formId == formID) { $(document).on('change', '#input_'+formID+'_'+fieldCheck, function() { displayMessage(); }); function displayMessage() { var selectedCountry = $('#input_'+formID+'_'+fieldCheck).val(); switch (selectedCountry) { case 'DE': $('#input_'+formID+'_'+fieldResult).val('Welcome Germany!'); break; case 'Italie': $('#input_'+formID+'_'+fieldResult).val('Welcome Italy!'); break; case '': $('#input_'+formID+'_'+fieldResult).val('Where do you come from?'); break; default: $('#input_'+formID+'_'+fieldResult).val(''); break; } } displayMessage(); } });
In addition, you can make the display field ‘read only’ by using a Custom CSS Class, which is useful if you need to save this value.
Add this PHP code to your plugin :
<?php /** * Add read only GF field property, by using class 'gf_readonly' */ add_filter( 'gform_pre_render_3', 'add_readonly_script' ); function add_readonly_script( $form ) { ?> <script type="text/javascript"> jQuery(document).on('gform_post_render', function(){ jQuery(".gf_readonly input").attr("readonly","readonly"); }); </script> <?php return $form; } ?>