[How to] Conditionally Display Additional Form Fields Based On Dropdown Selection


Userlevel 6
  • Former Unbouncer
  • 198 replies

Want to avoid scaring someone off with too many form fields? Or maybe you want to collect an additional bit of information based on the context of a separate field (state/province based on the country selection, for example). Now you can with our latest addition to Tips and Scripts!

Introducing: Conditional Dropdown Fields :parrot:

This script will allow you to add a drop down field that will conditionally show which field appears next based on what the user chooses.

You can see this in action (built in Unbounce) here:
http://unbouncepages.com/conditional-reveal/

And the State/Province example here:
http://unbouncepages.com/stateprovince-conditional-form-field/


Instructions

Click here to view the instructions

🚨
This is not an official Unbounce feature. This functionality is based entirely on third party code, and has only been tested in limited applications. Since this isn’t a supported Unbounce feature, our support team will be unable to assist if things go awry. So if you are not comfortable with HTML, Javascript and CSS, please consider consulting an experienced developer.


Step 1. Add the Javascript

You can find the javascript here: https://gist.github.com/RobertCam/0be9efb09a091e1880ffeb5edadf2d1a

Since this gets asked for fairly often in Support land, there is also a version of this script designed specifically to conditionally show a state or province field based on the selection of a country: https://gist.github.com/RobertCam/d7ac63b249eba28941872443cb9f2643

Step 2. Create the Form

If you haven’t already, add a dropdown field to the form on your page. The script will target the specified number of fields that follow the dropdown, hiding them and displaying the first field if the first dropdown option is selected, the second field if the second dropdown option is selected, ect…

If you are using the state/province version make sure that the state field comes before the province field in your form.

Step 3. Update the ID of the Dropdown Field, the box containing the form (if there is one), the Submit button, and the “count” Variable

Replace the ID in the script for the for the ID of dropdown field you wish to trigger the conditional logic on your page. Do the same with the submit button and any element the form is nested in. Then adjust the number for the the “count” variable to determine how many fields to conditionally show/hide.

Step 4. Adjust the Spacing of the Following Fields

If the conditional dropdown field is not the last field in your form you may need to slightly adjust the spacing for the fields that follow.

Change the number coming after the “space” variable in the code to adjust the vertical spacing of the following fields. Increasing the number will bring the fields up towards the top of the screen, decreasing it will push them down. It’s going to take a bit of trial and error (sorry).

The default in the script is for 5 fields. To get it working with 2 fields, for example, set the count to ‘2’ and the space to ‘15’.

**V.1 of this script is set to work only with two fields. You can find that here - https://gist.github.com/RobertCam/2e1fee450668037b237a450562fdcae3

You’re Done! :slowparrot:


Can’t see the instructions? Log-in or Join the Community to get access immediately. 🚀


Want to take your Unbounce landing pages + convertables to the next level?
:spinbounce: Check out the Ultimate List of Unbounce Tips, Scripts & Hacks


142 replies

Userlevel 6

If anyone is interested, thanks to @Daniele_Madia_Privat’s question, I’ve adapted the script to work with more than 2 fields. Shoot me a message if you’d like to conditionally display more than two fields with the script.

Userlevel 6
Badge +1

Oh man sooooo nice … sooooo useful!!! LOVE IT. 😍

Userlevel 3

Hi Amy!

I do have some code that can help you hide any element on your landing page between two hours.

Simply paste this code in the javascripts section of your page selecting ‘Head’ as the placement:

<script>
$(document).ready(function(){
    
   //Add the start and end time using the format hh:mm (24 hour format) Time is in UTC. 
	var startTime = '13:00';
	var endTime = '21:00';

	var curr_time = getval();

	if (curr_time > startTime && curr_time < endTime) {
    }else{
   
   //Change #lp-pom-box-15 for the ID of the element you want to hide.    
  		$('#lp-pom-box-15').hide();
    }
  
	function getval() {
    	var currentTime = new Date()
    	var hours = currentTime.getUTCHours()
    	var minutes = currentTime.getUTCMinutes()
    	if (minutes < 10) minutes = "0" + minutes;
    	var current_time = hours + ":" + minutes;
    	return current_time;
	}  
});
</script>

Now, change the ‘startTime’ and the ‘endTime’. This is the period of time the element will be visible on the page. Keep in mind this times are in UTC, to make sure it’s the same time all around the world. There are many resources on line to help you find your UTC time, here’s one of them.

Don’t forget to change #lp-pom-box-15 for the ID of your own box or element, save and republish.

That’s it! Please give it a try and feel free to reach out if you have any other questions. Keep in mind we are not always able to support this type of unofficial workarounds, but we are always happy to take a look and at least try to point you in the right direction 🙂

Have a great day, Amy!

Userlevel 6

@Daniele_Madia_Privat Feel free to direct message me and include the page URL and I can take a look for you 🙂

Userlevel 7
Badge +1

@Rob this is hot fire!!! 🔥

Ok done with 4 options

Hey @Amy_Sera,

Have you considered this script instead? It allows you to start with the easy questions and work your way up to the meaty questions. If you give this a try I’d love to hear how it works out for you!

Thank you both so much, this is awesome! If it ever makes it into a feature it would be good to have the flexibility to combine day of week. So hide it monday for these hours, tuesday for those hours, etc.

Hi Rob,

I’ve set up a giveaway form where I’d like multiple fields to reveal at the same time if the user wants the giveaway. You can see the form here: https://alwaysforward.angelusnews.com/newsletter-test/

If the user elects “no” I’d like for the user to just be able to input their email and for no other form fields to show. If the user elects “yes,” I’d like for the rest of the form fields to be revealed at the same time (5 other fields that collects their name, address, city, state, and zip).

Is there an edit to the code I can make to have this happen? Thanks!

Dominick

I’d like this, too, @Rob !

I need two fields (maybe 3) to show if a user selects ‘yes’ in the dropdown and nothing to happen if they select ‘no.’

Hi Rob - I actually figured out that this already does this! So sorry, thanks for the great script!

Userlevel 2
Badge +1

I’ve noticed that the ‘State/Province’ example will cause form submission issues with newer Unbounce pages (newer pages use HTML 5 validation and the form structure is slightly different), so I wrote little fix.

Here’s the script I used for anyone who’s interested 🙂

Be sure to modify the variable values.

<script>
/*
Unbounce Community :: Tips & Scripts :: Conditional State/ Province Form Field Based on Dropdown 
TS:0002-04-060
***********************
Do not remove this section. It helps our team track useage of external workarounds.
*/  
  
  // Conditional Reveal state/province field based on selection of the country dropdown
  // Make sure the "state" field is placed after the country dropdown. Place the province field after the state field
  
  $(document).ready(function(){(function(){
  var submitBtn = $("#lp-pom-button-171"); // Add ID of Submit Button
  var field = $("#Country");  // Add ID of Dropdown field
  var provinceFld = ("Province");  // Add ID of Province field (exclude #)
  var stateFld = ("State");  // Add ID of Province field (exclude #)
  
  var conField01 = field.parent().next();
  var conField02 = conField01.next();
  
  var topPos = conField01.position().top;
  conField02.css({top: topPos});        
  
  conField01.css("display", "none");
  conField02.css("display", "none");
  
  var fieldHeight = conField01.height();
  var space = fieldHeight*2+37;
  var halfSpace = space/2;
  
  var moreFields = $(conField02).nextAll();
  moreFields.animate({top: "-=" + space},0); 
  
  var i = true;
  $(field).change(function() {
     if ($(this).val() == "United States") {
      conField01.fadeIn("slow");
      conField02.fadeOut("slow");
      document.getElementById(stateFld).setAttribute("required", "");
      document.getElementById(provinceFld).removeAttribute("required");
      module.lp.form.data.validationMessages.State = "Please select a State"
      if (i) {
        fieldAdjust();
        i = false;
      }
    } else if ($(this).val() == "Canada") {
      conField01.fadeOut("slow");        
      conField02.fadeIn("slow");
      document.getElementById(provinceFld).setAttribute("required", "");
	  document.getElementById(stateFld).removeAttribute("required");
      module.lp.form.data.validationMessages.Province = "Please select a Province"
      if (i) {
        fieldAdjust();
        i = false;
      }
    } else {
      i = true;
      conField01.fadeOut("slow");
      conField02.fadeOut("slow");
      document.getElementById(provinceFld).removeAttribute("required");
	  document.getElementById(stateFld).removeAttribute("required");
      if (conField01.css('display') == 'block' || conField02.css('display') == 'block') {
        moreFields.animate({top: "-=" + halfSpace}, 600);
        submitBtn.animate({top: "-=" + halfSpace}, 600);
      }  
    }
  });
  var fieldAdjust = function() {
    moreFields.animate({top: "+=" + halfSpace}, 600);
    submitBtn.animate({top: "+=" + halfSpace}, 600);
  }
})();   });
</script>

Hi Rob,

Don’t know whether this is doable. or not.

Is there a way to only have the reveal happen off one of the dropdown options?

So basically, If I had a dropdown called ‘How do you stay healthy’ and within that dropdown 4 or 5 options so Cycling / Gym / Running / Other. But I only want ‘Other’ to trigger the reveal. Is that doable?

Also, is the code capable of being used on more than one dropdown? I have a form currently that has several text input fields, then 3 dropdowns, some more text fields and finally a send button. Each of the 3 dropdowns has the ‘Other’ option which I would like reveal it’s own text field.

I hope all that makes sense?

Thanks for any help.

Gary

Hello,

Thank you very much for the script. Im new here, I have no knowledge in doing jscript, I copied the script that was given but I cant seem to make it work with the below conditions, may I ask for help for the script on this one please:

  • When I select US, it should show City, State, Postcode fields.
  • Else, it hides city, state, postcode fields.

Thank you for the help!

Opps, I just read one reply with the same condition. Im checking the provided solution. Im all good thank yoU!

Userlevel 6

Looks like you got this figured out already @Daniele_Madia_Privat 🙂

For anyone else reading this, you can easily use this multiple times by copy/pasting the javascript and changing the ID to match the new dropdown and the submit button.

I’m trying with no sucess to integrate conditional display with Dynamic Form Confirmation URL’s Using Browser Redirects. For example my goal is a form with “select state/country” -> after selection appear the form with all city of selected country -> selection city with redirect to a specific url.com/city. Anyone have an idea how to do that?

Rob, you da real MVP.

Userlevel 6

Thanks @stefanei! How many fields do you need this to work with? It’s for sure possible but requires a bit of reworking the script how it’s currently written. I’m working on making it more dynamic, but I can help you out with this one in the meantime.

Thank you! If the script could work with 5 fields at this point that would be great!

Userlevel 6

Thanks for requesting this @stefanei! I put together a version of the script that will allow you to choose the number of fields to reveal. Change the number after “var count =” to the number of fields you need to conditionally hide. It ill work the same way in that it will apply to the fields immediately following the dropdown.
You can grab the updated script here - https://gist.github.com/RobertCam/0be9efb09a091e1880ffeb5edadf2d1a

The number for the space variable will slightly adjust the spacing of the visible fields after the dropdown (if there are any). I’ve defaulted it all to work with 5 fields. But if you change the number you may need to play around with the space variable a bit to get it perfectly placed.

@ltaylor You can definitely have fields that are always visible after the conditionally displayed field. Here’s an example: http://unbouncepages.com/conditional-dropdown-multiple-fields/

🙂

Userlevel 6

Hi @Amy_Sera, you could potentially adapt this code for that purpose for sure. It would take a bit of customization. This older workaround from @noah does exactly what you need as well, so you could always just include both pieces of code on the page. https://gist.github.com/noahub/ee4fd2a1eb8b3096cf29952548ebedab

Let me know if there is anything I can do to help!

So what if you wanted nested hidden fields. So I’m basically just showing one field at a time? The idea would be that rather than shoving a form at them, we ask a series of softball questions to get them engaged, and once they’ve answered 3 questions we show them the full lead form?

Awesome! I’ll check it out and let you know. While I have you, do you have any tips for hiding a box based on the time of day? Like if I have a floating phone number click to call box, but my call center closes at a certain time, it would be nice to hide that box after 6pm MST for example.

Ahhhhhh, very interesting use case. I’m sure this would be possible with a bit of code. @Vic / @Rob / @Noah - you know of anything off the top of your head?

Awesome, @Vic! Let’s build this into an official Tip & Script that we can add to the library. 🙂

Reply