[How To] Add A Multi-Step Form 2.0



Show first post

224 replies

Did a bit more testing and I think I cracked the code (pun intended):

<script>
  function UnbounceMultiStep(form, options) {

  // Validate arguments
  if ( !form.is('.lp-pom-form form') )
return console.error('jQuery.unbounceMultiStep must be called on an Unbounce form.');

  if ( typeof options !== 'object' )
return console.error('No options were passed to jQuery.unbounceMultiStep');

  this.options = options;

  // Store DOM elements
  this.form = form;
  this.formContainer = this.form.closest('.lp-pom-form');
  this.fields = this.form.find('div.lp-pom-form-field');
  this.fieldsByStep = [];
  this.currentStep = 0;
  this.forwardButton = this.formContainer.find('.lp-pom-button').eq(0);
  //this.validationError = $('.lp-form-errors');
  
  // Verbiage
  this.text = {};  
  this.text.next = this.options.nextButton;
  this.text.showSteps = this.options.showSteps;
  this.text.back = this.options.backButton;
  this.text.submit = this.forwardButton.children('span').html();

  // Call constructor method
  this.init();
}

UnbounceMultiStep.prototype.init = function() {
  var _this = this;

  this.formContainer.addClass('multistep initial');
  this.form.attr('id', 'fields');

  // Add progress bar
  this.formContainer.prepend('<div id="progress-bar"></div>');
  this.progressBar = lp.jQuery('#progress-bar');

  // Replicate Unbounce's field spacing
  var height = parseInt( this.fields.eq(0).css('height'), 10);
  var top = parseInt( this.fields.eq(1).css('top'), 10);
  this.fields.css('margin-bottom', (top - height) + 'px');
  this.progressBar.css('margin-bottom', (top - height) + 'px');

  // Set up fieldset elements for each step
  for ( var i = 0 ; i < this.options.steps.length ; i ++ ) {
console.log('Adding new fieldset.');
this.form.append('<fieldset></fieldset>');
  }
  this.steps = this.form.find('fieldset');
  this.steps.addClass('step');

  // Sort fields into new steps
  var currentField = 0;
  for ( currentStep = 0 ; currentStep < this.options.steps.length ; currentStep ++ ) {
this.progressBar.append('<div class="step">' +
                        '<span class="num">'+ (currentStep + 1) +'</span>' +
                        '<span class="title">'+ this.options.steps[currentStep].title +'</span>' +
                        '</div>');
this.fieldsByStep[currentStep] = [];
for ( i = 0 ; i < this.options.steps[currentStep].fields ; i ++ ) {
  console.log('Field ' + currentField + ' -> step ' + currentStep );
  this.fields.eq( currentField ).appendTo( this.steps.eq( currentStep ) );
  this.fieldsByStep[ currentStep ].push( this.fields.eq( currentField ) );
  currentField ++;
}
  }

  // Add any remaining fields to last step
  if ( currentField < this.fields.length ) {
currentStep --;
for ( i = currentField ; i < this.fields.length ; i ++ ) {
  console.log('Field ' + currentField + ' -> step ' + currentStep );
  this.fields.eq( currentField ).appendTo( this.steps.last() );
  this.fieldsByStep[ currentStep ].push( this.fields.eq( currentField) );
  currentField ++;
}
  }
  console.log(this.fieldsByStep);

  this.progressBarItems = lp.jQuery('#progress-bar .step');

  // Add a back button
  this.backButton = this.forwardButton.clone().insertBefore(this.forwardButton);
  this.backButton.addClass('back-button');
  this.backButton.children('span').html(this.text.back);

  // Only validate fields that are in current step
  $.each(window.module.lp.form.data.validationRules, function() {
if ( this.required === true ) { this.required = {
  depends: function () { return $(this).is('.active :input')}
};
  }
  });

  // Add event listeners
  $(function() {
   _this.backButton.unbind('click touchstart').bind('click.unbounceMultiStep', function(e) {
  _this.backHandler();
});

//_this.backButton.removeAttr('href');	
_this.backButton.attr('href','#request');

_this.forwardButton.unbind('click touchstart').bind('click.unbounceMultiStep', function() {
  _this.forwardHandler();
});

//_this.forwardButton.removeAttr('href');
_this.forwardButton.attr('href','#request');
  });

  // Show first step
  this.goToStep(0);
};

UnbounceMultiStep.prototype.goToStep = function ( newStep ) {
  // Make sure we aren't going to a steΩp that doesn't exist
  if ( newStep < 0 || newStep >= this.steps.length ) return false;

  this.steps.eq( this.currentStep ).removeClass('active').hide();
  this.steps.eq( newStep ).addClass('active').fadeIn();

  this.progressBarItems.eq( this.currentStep ).removeClass('active');
  this.progressBarItems.eq( newStep ).addClass('active');

  this.formContainer.toggleClass('initial', newStep === 0);

  // Update the label of the forward button
  var current = parseInt(newStep) + 0;
  var total = this.steps.length;
  var nextText = this.text.showSteps ? this.text.next + ' (Step ' + current + ' of ' + total + ")" : this.text.next;
  var submitText = this.text.submit;
  
  var forwardButtonLabel = ( newStep === this.steps.length - 2 ) ? submitText : nextText;
  console.log(forwardButtonLabel);
  this.forwardButton.children('span').html(forwardButtonLabel);

  this.currentStep = newStep;
};

UnbounceMultiStep.prototype.validate = function () {
  return this.form.valid();
};

UnbounceMultiStep.prototype.forwardHandler = function () {

  // Prevent going to next step or submitting if step isn't valid
  if ( !this.validate() )
  {$('.lp-form-errors').appendTo( '#' + window.module.lp.form.data.formContainerId );
return false;}
  
  
  if ( this.currentStep === this.steps.length - 2 ) {
this.form.submit();
this.goToStep(0);
  }else{
//$('#reg_nurse_disclaimer').hide();	
this.goToStep( this.currentStep + 1 );
  }
};

UnbounceMultiStep.prototype.backHandler = function () {
  this.goToStep( this.currentStep -1 );

  // Refresh the validation status
  this.validate();
};

//jQuery plugin
lp.jQuery.fn.unbounceMultiStep = function(options) {
  window.ms = new UnbounceMultiStep(this, options);
  return this;
};
</script>

Hi there,

I’m trying to reduce an existing multi-form script that has 3 steps down to 2 steps. I’m not a developer, and I’ve found myself a bit stuck! I have a feeling it’s a matter of changing a minor element of the script.

Any help would be much appreciated!

Here’s the existing script:

<script>
  function UnbounceMultiStep(form, options) {

  // Validate arguments
  if ( !form.is('.lp-pom-form form') )
    return console.error('jQuery.unbounceMultiStep must be called on an Unbounce form.');

  if ( typeof options !== 'object' )
    return console.error('No options were passed to jQuery.unbounceMultiStep');

  this.options = options;

  // Store DOM elements
  this.form = form;
  this.formContainer = this.form.closest('.lp-pom-form');
  this.fields = this.form.find('div.lp-pom-form-field');
  this.fieldsByStep = [];
  this.currentStep = 0;
  this.forwardButton = this.formContainer.find('.lp-pom-button').eq(0);
  //this.validationError = $('.lp-form-errors');
  
  // Verbiage
  this.text = {};  
  this.text.next = this.options.nextButton;
  this.text.showSteps = this.options.showSteps;
  this.text.back = this.options.backButton;
  this.text.submit = this.forwardButton.children('span').html();

  // Call constructor method
  this.init();
}

UnbounceMultiStep.prototype.init = function() {
  var _this = this;

  this.formContainer.addClass('multistep initial');
  this.form.attr('id', 'fields');

  // Add progress bar
  this.formContainer.prepend('<div id="progress-bar"></div>');
  this.progressBar = lp.jQuery('#progress-bar');

  // Replicate Unbounce's field spacing
  var height = parseInt( this.fields.eq(0).css('height'), 10);
  var top = parseInt( this.fields.eq(1).css('top'), 10);
  this.fields.css('margin-bottom', (top - height) + 'px');
  this.progressBar.css('margin-bottom', (top - height) + 'px');

  // Set up fieldset elements for each step
  for ( var i = 0 ; i < this.options.steps.length ; i ++ ) {
    console.log('Adding new fieldset.');
    this.form.append('<fieldset></fieldset>');
  }
  this.steps = this.form.find('fieldset');
  this.steps.addClass('step');

  // Sort fields into new steps
  var currentField = 0;
  for ( currentStep = 0 ; currentStep < this.options.steps.length ; currentStep ++ ) {
    this.progressBar.append('<div class="step">' +
                            '<span class="num">'+ (currentStep + 1) +'</span>' +
                            '<span class="title">'+ this.options.steps[currentStep].title +'</span>' +
                            '</div>');
    this.fieldsByStep[currentStep] = [];
    for ( i = 0 ; i < this.options.steps[currentStep].fields ; i ++ ) {
      console.log('Field ' + currentField + ' -> step ' + currentStep );
      this.fields.eq( currentField ).appendTo( this.steps.eq( currentStep ) );
      this.fieldsByStep[ currentStep ].push( this.fields.eq( currentField ) );
      currentField ++;
    }
  }

  // Add any remaining fields to last step
  if ( currentField < this.fields.length ) {
    currentStep --;
    for ( i = currentField ; i < this.fields.length ; i ++ ) {
      console.log('Field ' + currentField + ' -> step ' + currentStep );
      this.fields.eq( currentField ).appendTo( this.steps.last() );
      this.fieldsByStep[ currentStep ].push( this.fields.eq( currentField) );
      currentField ++;
    }
  }
  console.log(this.fieldsByStep);

  this.progressBarItems = lp.jQuery('#progress-bar .step');

  // Add a back button
  this.backButton = this.forwardButton.clone().insertBefore(this.forwardButton);
  this.backButton.addClass('back-button');
  this.backButton.children('span').html(this.text.back);

  // Only validate fields that are in current step
  $.each(window.module.lp.form.data.validationRules, function() {
    if ( this.required === true ) { this.required = {
      depends: function () { return $(this).is('.active :input')}
    };
  }
  });

  // Add event listeners
  $(function() {
   _this.backButton.unbind('click touchstart').bind('click.unbounceMultiStep', function(e) {
      _this.backHandler();
    });
    
    //_this.backButton.removeAttr('href');	
    _this.backButton.attr('href','#request');

    _this.forwardButton.unbind('click touchstart').bind('click.unbounceMultiStep', function() {
      _this.forwardHandler();
    });
    
    //_this.forwardButton.removeAttr('href');
    _this.forwardButton.attr('href','#request');
  });

  // Show first step
  this.goToStep(0);
};

UnbounceMultiStep.prototype.goToStep = function ( newStep ) {
  // Make sure we aren't going to a steΩp that doesn't exist
  if ( newStep < 0 || newStep >= this.steps.length ) return false;

  this.steps.eq( this.currentStep ).removeClass('active').hide();
  this.steps.eq( newStep ).addClass('active').fadeIn();

  this.progressBarItems.eq( this.currentStep ).removeClass('active');
  this.progressBarItems.eq( newStep ).addClass('active');

  this.formContainer.toggleClass('initial', newStep === 0);

  // Update the label of the forward button
  var current = parseInt(newStep) + 2;
  var total = this.steps.length;
  var nextText = this.text.showSteps ? this.text.next + ' (Step ' + current + ' of ' + total + ")" : this.text.next;
  var submitText = this.text.submit;
  
  var forwardButtonLabel = ( newStep === this.steps.length - 1 ) ? submitText : nextText;
  console.log(forwardButtonLabel);
  this.forwardButton.children('span').html(forwardButtonLabel);

  this.currentStep = newStep;
};

UnbounceMultiStep.prototype.validate = function () {
  return this.form.valid();
};

UnbounceMultiStep.prototype.forwardHandler = function () {

  // Prevent going to next step or submitting if step isn't valid
  if ( !this.validate() )
  {$('.lp-form-errors').appendTo( '#' + window.module.lp.form.data.formContainerId );
    return false;}
  
  
  if ( this.currentStep === this.steps.length - 1 ) {
    this.form.submit();
    this.goToStep(0);
  }else{
    //$('#reg_nurse_disclaimer').hide();	
    this.goToStep( this.currentStep + 1 );
  }
};

UnbounceMultiStep.prototype.backHandler = function () {
  this.goToStep( this.currentStep -1 );

  // Refresh the validation status
  this.validate();
};

//jQuery plugin
lp.jQuery.fn.unbounceMultiStep = function(options) {
  window.ms = new UnbounceMultiStep(this, options);
  return this;
};
</script>
Badge

Hello @Noah ,
i used this script to build a multistep form and works fine for me. I just want to ask, is it possible to validate a textarea with character limit. I user to write at least 100 character. Before use the multistep form script, i used a script to validate the textarea. But it is not working after use multistep form script.
Kind Regards

Hi,
First of all, I would like to send a massive high five for job well done with this script. Working like a charm.

One thing that I would love to change (any ideas how?) is that if you press left or right direction button it takes u back or forward respectively in the form. It proved to be counter productive as a lot of people use direction buttons to navigate through text.

Anyone knows how to fix that?

Thanks a lot in advance 🙂

Userlevel 5
Badge +4

Be careful with this script, with the removal of Jquery in the form you need the following par in the JS of otherwise you’ll have two errors messages.

//add error span
errorSpan.classList.add('hide');
errorSpan.style.color = '#FFFFFF';
errorSpan.style.position = 'absolute';
var labelHeight;
if(allFields[0].querySelector('label')){
labelHeight = allFields[0].querySelector('label').clientHeight;
}else {
labelHeight = 35;
}
errorSpan.style.top = '-'+labelHeight+'px';  
formContainer.appendChild(errorSpan);

Maybe @Noah can confirm this as i’m not a JS expert ?

I’m having the same exact problem.

I’m also very interested in where to set the height/max @Eliot_Sell!

I actuallly totally agree with @mike22rtn. Even though this script is already totally awesome, it would be great if you could 2-3 questions at a time instead of only 1, so that to the user it “feels” like only 2-3 pages of a survey, even if it’s the same amount of questions.

Also @Noah do you know if there’s a way to track individual fb pixel standard events for each question? This would be IMMENSELY valuable and is a gaping hole in the entire survey/quiz/funnel software industry. None of the dynamic survey tools allow for tracking conversions INSIDE the survey, they only track the start and end. But for example, to better optimize fb campaigns, I want to be able to put a ViewContent pixel on the first question, an AddToCart pixel on the second question, a Lead pixel on the 3rd question, etc. etc.

Hi Matteo.
I’m afraid we are talking about two different scripts. My script is the original one of this thread & yours is the one posted by Caroline right?

I’m afraid I don’t use the multi-step form you are trying to set up so I can’t help you!

P.S. I do recommend using the multi-step form (the one this thread is supposed to be about!).
It’s brilliant & easy to set up.

Scroll all the way to the top and try it out.

Hi,

Thanks for this info!

I added a button and looked in the code for lines saying ‘Var backButton =…’ and 'var nextButton =…" so that I can add the ID like you showed, but they are not there. Is this something I can add myself without ‘breaking’ the script? Where should I add it exactly?

Regards,

Ahhh. I see. No, you create the back and next buttons yourself. You can style them however you like.

When you create the two buttons you have to find their ID’s & make sure that is what’s in your script.

So here’s my back button :

back%20button
back button.PNG966x305 86.8 KB

Here’s my next button:

next%20button
next button.PNG848x274 47.6 KB

And you can see I’ve put those in the script here:

multi-step%20script
multi-step script.PNG977x127 7.61 KB

This is what it looks like when it’s up and running:
multi-step%20styling

I’ve just pointed out a couple of other things I’ve done.

I’ve but a box around the progress bar and I’ve changed the colour of the step counter to match the styling of my page. The box is as simple as creating it and arranging it behind the form in the right spot.

Changing the colour is in the script. It’s here:step%20counter%20text

In that picture you can see that you can also change the progress bar colour (the from: & the to: values).

Hi,

In the guide I found, nothing was said about creating a back button. This appears to be automatically generated. Can I get you some script screenshots to make this easier?

Regards,

Have you made sure the back button & the form button are away from each other or are not layered on top of each other?

I would try dragging your back button well away from the form submit button and trying that to see if the problem persists.

Hi,

Thanks for this how-to. I implemented it, but stumbled upon a mistake: when testing the ‘Back’ button, the form is submitted, which of course shouldn’t be the case. Anyone else experiencing this problem? Is there a solution for this?

Regards,

Matteo

Userlevel 2
Badge

Hi All Community Members,
I see that has been an issue for many people using unbounce here. Each and every requirement is different here so we can’t probably jump to a fixed conclusion for now.

I have found a way to alter the script and show as many fields you need in any number of steps.

So if you need any help with the form: you can reach out to me through my email: reckless.sam@gmail.com

with subject: Unbounce Community - Multi Step Form Help

I will get back to you within shortest time possible and update your scripts at a genuine price.

If ii find a solution that could be used for all then i will post it here for all the members surely.

Looking forward to help you out with the forms! 🙂

Thanks!

Awesome! Is there by any chance a way to automatically jump to next question without clicking “next” button? sthing like this: https://audimagnet.com/comparador/?v=1&adsid=_19630420300699590 That’d be an extra-awe

hello,

someone could please share me a template, i have some pb to create a form with several steps
thx

Right now the script won’t allow the business email only script at the same time. I have to remove the business script and uncheck “validate as an email address”

It will give this error: https://pasteboard.co/HA4JEpL.png

Any work around for this?

Is it possible to mix and match checkboxes, text-fields and drop-down menus with this code? Because I’m trying to do just that, and I can’t get it to work.

Hello @Noah
I have downloaded your lastest version of the script and i am still getting stuck at the drop down menu.
http://audibel.it/campaign/batterie-gratis/
Can you please help? What am i doing wrong? Thanks!

Userlevel 5
Badge +2

Haven’t heard of that one before @ian-idplans - Feel free to message me for more assistance.

I’m having an issue where it will not let me select radio buttons when it’s live.

@Marissa_Rustici

You can add it in the CSS. Just pick an appropriate height.

16%20AM

@Eliot_Sell, can you point to where I would change the max height? I think it’s in the below section somewhere.

// Replicate Unbounce’s field spacing
var height = parseInt( this.fields.eq(0).css(‘height’), 10);
var top = parseInt( this.fields.eq(1).css(‘top’), 10);
this.fields.css(‘margin-bottom’, (top - height) + ‘px’);
this.progressBar.css(‘margin-bottom’, (top - height) + ‘px’);

Hi, @Caroline

Sorry I wasn’t clear enough with the question. I have removed the back button from the script since I don’t need it for what I am currently working on. The 2 buttons I want to make changes to are the next button and then the submit form button.

You can see the form here http://unbouncepages.com/king-remodeling-front-door/

So basically when I click the “Next Step” button and get to the second part of the form I want to change the width and position of the “Request a Quote” button to better fit the form since currently it just doesn’t work good.

If you know a quick fix for this I would really appreciate it. Thanks for your time.

Reply