Gravity forms fields - how to apply external Javascript to fields?

Qwerty picture Qwerty · Mar 12, 2014 · Viewed 8.7k times · Source

Using the WordPress plugin Gravity Forms, I have created a form with text fields. For some of the text fields I would like to apply Javascript that allows a text field to be autocompleted.

How can I add Javascript for a fields to take the effect? I know I would need to edit my WP site theme's functions.php file. But not sure which part

Also I'm not sure how to specify the id for the field within gravity forms code. I could apply the JS by going:

document.getElementId("IDSpecified"); 

Any one have any idea how to do this?

Answer

mdrewlo picture mdrewlo · Mar 13, 2014

Take a look at the Gravity Forms developer documentation. The Gravity Forms filter gform_register_init_scripts can be used to execute custom scripts on a form. It can be implemented in your themes functions.php.

Description

Tap into Gravity Forms' "initalization scripts" functionality and register your own scripts to run inline with Gravity Forms. Scripts added via the GFFormDisplay::add_init_script() function will be output with the form(s) they are registered for.

Example (Simplified)

<?php
add_filter('gform_register_init_scripts', 'gform_my_function');
function gform_my_function($form) {

    $script = '(function($){' .
        '$('.gf_yourfield input').each(function(){
          // do something
         });' .
    '})(jQuery);';

    GFFormDisplay::add_init_script($form['id'], 'gform_my_function', GFFormDisplay::ON_PAGE_RENDER, $script);
    return $form;
}
?>