How to skip a form stage in a multi stage form

Created by Phil Kurth, Modified on Fri, 09 Dec 2022 at 10:21 AM by Phil Kurth

You may skip form stages using some custom JavaScript. The following example demonstrates how to skip a page. Note that there is no condition in this example but you can add whatever checks you need where specified.


acf.addAction('af/form/page_changed', function (pageTo, pageFrom, form) {
  
  // If changing to the second page (page numbers are zero-indexed), jump to page 3.
  if (pageTo === 1) {
    
    // …place any custom checks/conditions you need here…
    
    // To access field value using ACF's JS API, try something like the following:
    // let value = acf.getField( acf.get_field( 'your_field_name' ) ).val();
    
    // Jump to page 3.
    af.pages.changePage(2, form);
  }
});


Skipping stages that have conditionally hidden fields

If you have a form stage where all the fields may be hidden due to conditional logic on the form, you may wish to skip the page entirely. You may do this using the following snippet: 


<?php 

// Start by hooking into the Advanced Forms form enqueue hook. This ensures that the script 
// is only loaded when a form is being displayed.
add_action( 'af/form/enqueue', function ( $form, $args ) {

  // If we need to run this only on a specific form, check for the form key and return 
  // early if we don't have a match.
  //if ( $form['key'] !== 'FORM_KEY_HERE' ) {
  //  return $form;
  //}

  ?>
  <script>
    // Run our script on jQuery's document ready event. This ensures that the 
    // global `acf` variable is available.
    jQuery(function ($) {

      // Use a JS hook to run the script after each page change.
      acf.addAction('af/form/page_changed', function (pageTo, pageFrom, form) {

        // Get all fields on the current page.
        const currentPageFields = form.pages[pageTo].$fields;

        // Check if any of the current page fields are visible.
        const pageHasVisibleFields = !!currentPageFields.filter(':visible').length;

        // Determine if form page change is forward or backward.
        const isForward = pageTo > pageFrom;

        // If no visible fields are found on this page, skip to the next.
        if (!pageHasVisibleFields) {
          const nextPage = isForward ? pageTo + 1 : pageTo - 1;
          af.pages.changePage(nextPage, form);
        }

      });

    });
  </script>
  <?php
}, 10, 2 );

Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select atleast one of the reasons

Feedback sent

We appreciate your effort and will try to fix the article