gmeben gmeben - 10 months ago 48
Javascript Question

Gravity Forms - Get Current Page Number

I have a multi-page form.

I would like to execute some custom JavaScript on the last page of this form. Theoretically, all I have to do is retrieve the current page number and write a conditional.

Simple, right? Apparently not.

My original workaround was like this:

if ($('gform_page').last().css('display') !== 'none') {
// perform custom scripts now that the last
// Gravity Form page is being shown

on every element I've tried this on within the form. Custom scripts were being fired every time the user hit the "Next" button. No cigar.

Then, after reviewing the Gravity Forms documentation, I found two useful-looking events:

However, the documentation gives no instruction on how to access the parameters.

jQuery(document).bind('gform_page_loaded', function(event, form_id, current_page){
// returns nothing when loaded in the footer
// returns [Object, object] when placed in an HTML field in the form

In addition to not having the correct code, I also suspect I don't have the code in the correct place as I have also fruitlessly tried the following in functions.php and in header.php (as the documentation suggests):

function enqueue_custom_script($form, $is_ajax){
if ($is_ajax) :
echo '<script>console.log(current_page);</script>';
add_action("gform_enqueue_scripts", "enqueue_custom_script", 10, 2);


What code do I need to retrieve the current page number, and more importantly, where do I place that code?

Answer Source

I got it.

The function rgpost is, apparently, crucial in accessing the current page number. After some muddling around on my own, I was able to get the following code working in both functions.php and just before the wp_head() function in header.php.

function run_script_on_last_page($form) {
    if (!is_admin()) {
        $current_page = rgpost('gform_source_page_number_' . $form['id']) ? rgpost('gform_source_page_number_' . $form['id']) : 1;
        if ($current_page == 10) {
            wp_enqueue_script('custom_script', get_template_directory_uri() . '/js/custom_script.js', array('jquery'), null, true);
add_action('gform_enqueue_scripts_63', 'run_script_on_last_page');

If you're copy/pasting the code above, make sure to:

  • replace 10 with the page you want to check
  • ensure your parameters are correct in wp_enqueue_script
  • replace 63 with your form ID

Some resources I found useful: