I needed a way to dynamically generate the birthday fields so I didn't have to remember to change all of them across multiple forms every year on January 1st. I have 6 forms each asking for 10 birthdays. Updating 60 fields manually is not something I want to do on New Year's Day.
My disclaimer: I'm no expert on jQuery. Use this at your own risk. Please suggest improvements.
Here's my situation...
This travel agency needs to ask for the birthdates of up to 10 people. The "lead guest" has to be 18 years old or older. All of the other guests can be any age. The "Name" of my birthday fields in RSForm! Pro are "DOB" (short for Date Of Birth) followed by a number. The lead guest would have DOB1, the next guest would have DOB2, the next DOB3, and so forth. RSForm! Pro then gives an ID to the month, day, and year fields like...
Month: id="DOB1m"
Day: id="DOB1d"
Year: id="DOB1y"
My form is also grabbing the logged in user's profile info from Community Builder and pre-filling the form so it takes less time for the user to fill out. I had to preserve that information first, remove the existing options in the select field, write new options, then pre-select the option that matches the Community Builder info (if at all).
Go to Form Properties > CSS and Javascript and paste this code into the Javascript area.
<script>
$(function () {
// Dynamically generates the year options so it doesn't have to be updated every January 1st
var x, y, z;
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; // used as a counter - I had 10 birthdates. If you have 4 in a form then just put [1, 2, 3, 4].
// Preserve pre-populated values from Community Builder first or JS below will overwrite
var otDOBs = [0];
$.each(numbers, function(index, value){
otDOBs.push($("#DOB"+value+"y").val());
});
// Clear out year options
$.each(numbers, function(index, value){
$("#DOB"+value+"y option").remove();
});
// Set date/year variables
var year = new Date().getFullYear();
var min = year + 1; // +1 because of pregnancies
var min18 = year - 18; // Must be 18 or older
var max = year - 100; // Arbitrary - I figured no one older than 100 would be traveling to theme parks
// Create new options
$.each(numbers, function(index, value){
var dobId = $("#DOB"+value+"y");
dobId.append(new Option("Year", ""));
if (value === 1) { // Create options for Lead Guest
for (x = min18; x >= max; x--) {
dobId.append(new Option(x, x));
if (x == otDOBs[value]) {
dobId.val(x).attr("selected", "selected");
}
}
} else { // Create options for other guests
for (y = min; y >= max; y--) {
dobId.append(new Option(y, y));
if (y == otDOBs[value]) {
dobId.val(y).attr("selected", "selected");
}
}
}
});
});
</script>
I'm not sure why, but my "for loops" work with "x >= max". Whenever I try "x <= max" (which is what I think it should be), the options don't get written into the code.