Skip to main content


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

I need exactly this too. The field would display “No” by default, and if the user selects "Yes’, then I need to show 2 additional fields for input.


Hi Rob. Can this script be modified to change either the 2nd drop down (or values inside of dropdown) depending upon the answer to the 1st drop down. To be clearer, my use case requires that the first drop down which contains a list of cities will determine the second drop down, which has a list of available agents within the selected city. Hope this makes sense! Thanks so much!


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


Hi @Rob I have a problem with this code. What I’m trying to do is if people say “Soy profesional de la salud mental” ("#soy_profesional_de_la_salud_mental") yes (#sí) don’t show an extra field. But if they answer no (#no) to show an extra field (Por_favor_cuentanos_por_qué_te_interesa_Psious).


I added the Javascript and when I test it and select “no” it creates a spacing but it’s blank.


Landing:

https://app.unbounce.com/2606601/variants/169916261/edit

Published URL as a test:

http://unbouncepages.com/cliente-directo/


Thanks


@Rob Thanks for all the detail in this post.

A few other community members have asked in this tread, but I have not seen a solution yet.


I am also looking for a way to make this script show two or more new form fields when you select “No” in the conditional dropdown and show none of them (hide) when you select “Yes”.


Any help here would be appreciated.


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 @Becky. Excellent! Managed to get this working for country/province. What if I want to add more than 2 options? This is the scenario:


USA - show states

Canada - show provinces Canda

Australia - show provinces Australia

New Zealand - show provinces NZ


Any help appreciated 😃


i cant do it 😑


Hello. I used this script but now the Submit button doesn’t work. Anyone else has experienced this issue? Here’s the link to my landing page https://www.universidad-icel.info/licenciatura


It’s because you’re requiring an input on each campus dropdown but, the user is only able to make a selection on the campus dropdown that is currently showing based on the degree selection input. I confirmed that’s the case by selecting a campus for each option in the degree selection input. You’ll have to make those individual dropdowns not required. From there you can just not require the input at all, try to make it look to users like it’s required, but do the validation or you could create your own custom validation that fires on the button click.


Hi Rob! Sorry in advance for the silly question, I’m new here!


I wanted to add a simple dropdow with two options and, if they choose option A, a hidden field is shown (as seen in the cat vs dog examples).


In the code I see that the IDs of the field are identified but I don’t see where the condition is configured (if option A> show field, else> none).


Could you help me with this? I am a little lost.


Thank u very much!


Hey Ana, I’m having the same problem right now. Could you solved this?


Thanks!


I got this working but can’t seem to figure out how to get my submit button to move lower once someone uses the dropdown?


Hey guys!


First off, absolutely love the code and the work you guys are putting in to make this work. Really makes the flash stand out and look amazing!


I made a video in my Unbounce playlist showing how to set this up…


Here is the link for those who want to see how to do this from start to finish:



Let me know if you have any questions!!


Ivan


Hello,


I’m hoping to get some information on this thread if it’s not too old - Jess advised me to post here.


The only thing I need different from the current code in the post is making my conditional dropbox 1 - 10 in an NPS survey with 3 different ranges (0 - 5, 6 - 8, 9 - 10). Each range will have a different comment prompt after selecting.


Is there anyone that has/ would know how to do this?


Thank you very much!


@Rob


Hi Rob,


Thank you for the script! However, I would like to create a dynamic form with the below behavior:

When someone clicks on the dropdown and select the first choice> 1 field is appearing below, and when someone chooses the second choice on the primary dropdown> 3 fields appear below and not just 1 as the script is now. Is it possible to create something like this?


Thanks in advance,

Carin


Hey @Carin,


Is it possible - yes.


However, you would have to write JS and CSS to account for the 3 extra fields in the 2nd option.


Also, depending on the fields, you might have to write your own validation or at least some logic in the JS that would not “force” you to fill out fields you are not actually seeing.


Last but not least, the CSS would help position the “hidden” fields once they show up and move up/down the submit button so you don’t cover it with the 3 extra fields.


Unfortunately, all of the above would depend on your particular form and there is no one-size fits all script that you can plug-in and use straight away.


Best,

Hristian


Hi @Hristian,


Thanks for your answer. Maybe you can help me with the JS, here is the form logic that I want it to be. Attached screenshots of the form. The logic of the form should be:



  1. A person choose between “Student” to “Industry Profesional” in the drop-down field (all the below fields should be hidden)

  2. If the person clicks on “Student”, below should be the drop-down field is shown - “Experience” and that’s it.

  3. If the person clicks on “Industry Profesional”, below should be the 3 fields shown - “Company Name”, “Job Title” and dropdown “Industrial Experience”.


Hope I made it clear enough and you can help me 🙂


Thank you!

Carin




This is great, is there anyway to have the conditional field be required after being revealed?


Hi @stevep,


Yes, you can have validation for fields that are visible and remove the validation for when the fields are not visible.




  1. First, you’ll need to remove the validation for the fields you are not showing. Here is an example for a checkbox field:


    const removeValidation = fields => { fields.forEach(element => { let items = document.getElementsByName(element); item = itemsm0]; item.removeAttribute('required'); item.removeAttribute('data-required'); item.type === 'checkbox' ? item.checked = false : item.value = ''; });




  2. Once they are shown, you’ll need to add the validation back in. Something like:


    const setValidation = field => { const items = document.getElementsByName(field); item = itemst0]; item.setAttribute('required', 'required'); item.setAttribute('data-required', 'data-required'); };




The above is just an example and you’ll need to write up the actual script but this should point you in the right direction.


Best,

Hristian


Is there a way I can have a selection of the dropdown open another dropdown?


Hi! I´m not a JS developer. I managed to use the following script. Can you help me add the validation script?


<script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>

<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.

La documentación de este script está en:
https://community.unbounce.com/t/how-to-conditionally-display-additional-form-fields-based-on-dropdown-selection/4430/22

https://gist.github.com/RobertCam/0be9efb09a091e1880ffeb5edadf2d1a

*/
(function(){
//ID of Submit Button
var submitBtn = $("#lp-pom-button-142");

//ID of dropdown field
var field = $("#provincia"); //escribir el ID con el #

// Number of fields to show/hide with dropdown
var count = 25;

// Adjust to fine tune placement of other form fields
var space = 27;

// Add the ID of the containing element (box) of your form if one exists
// Leave as "" if there is no box containing the form.
var box = "lp-pom-box-388";


// DO NOT EDIT CODE BELOW
var conFields = field.parent().nextAll().slice(0, +count);
var moreFields = field.parent().nextAll().slice(count);
var topPos = conFields.first().position().top;

// function to add the heights of all fields selected
$(conFields).each(function() {
$(this).css({top: topPos});
var height = $(this).outerHeight(true);
space = space += height;
});
// hide fields
conFields.css("display", "none");
// position other form fields
$(moreFields).each(function() {
$(this).animate({top: "-=" + space},0);
});

// function to show/hide fields
var z = true;
var box = $(box);
$(field).change(function() {

// adjust position of fields
var fieldAdjust = function(h, dir) {
if (dir == "up") {
$(moreFields).each(function() {
$(this).animate({top: "+=" + (h+5)}, 600)
});
submitBtn.animate({top: "+=" + (h+5)}, 600);
if (box != "") {
box.animate({height: "+=" + (h+5)}, 600);
}
} else if (dir == "down") {
$(moreFields).each(function() {
$(this).animate({top: "-=" + (h+5)}, 600)
});
submitBtn.animate({top: "-=" + (h+5)}, 600);
if (box != "") {
box.animate({height: "-=" + (h+5)}, 600);
}
}
}
var fieldGroup = range(0, count);
if ((this.selectedIndex - 1)in fieldGroup) {
var revealNum = this.selectedIndex-1;
} else {
var revealNum = -1;
}
var revealField = conFields.get(revealNum);
var otherFields = conFields.not(revealField);
var fieldHeight = $(revealField).outerHeight(true);
if (revealNum in fieldGroup) {
$(revealField).fadeIn("slow");
$(otherFields).fadeOut("slow");
if (z) {
fieldAdjust(fieldHeight,"up");
z = false;
}
} else {
$(revealField).fadeOut("slow");
$(otherFields).fadeOut("slow");
fieldAdjust(fieldHeight, "down");
z = true;
}

});
function range(start, end) {
var array = new Array();
for(var i = start; i < end; i++) {
array.push(i);
}
return array;
}
})();
</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


Reply