I have a multi page Gravity Form that is 4 questions, and each are multiple choice radio buttons. I am looking for a way to store each answer in an array so I can execute some functionality with that array after the form is submitted.
This is my most recent JavaScript to try to achieve this, but it is not working. I’m pretty stumped as to how to go about this, so any help would be appreciated.
// Global array to store answers
var answers = [];
// Function to capture answer for the current question and store it in the global array
function captureAnswer() {
// Find the currently visible page
var currentPage = jQuery('.gform_page_visible');
// Get the question number based on the page index
var questionNumber = currentPage.index() + 1; // Index is zero-based, so add 1
// Get the selected radio button value
var selectedValue = currentPage.find('.gfield--type-radio input:checked').val();
// Store the selected value in the global answers array
answers[questionNumber - 1] = selectedValue; // Subtract 1 to match array index
}
// Function to handle form submission
function handleFormSubmit(event) {
// Prevent the default form submission
event.preventDefault();
// Capture answer for the current question
captureAnswer();
// Check if all questions have been answered
var allQuestionsAnswered = answers.every(function(answer) {
return answer !== undefined;
});
// If all questions have been answered, log the answers
if (allQuestionsAnswered) {
console.log(answers);
} else {
console.log("Please answer all questions before submitting.");
}
// Allow the form submission to continue
this.submit();
}
(function($){
// Attach event handler to form submission
$('#gform_3').submit(handleFormSubmit);
// Attach event handler to radio button change
$('.gfield--type-radio input[type="radio"]').change(function() {
// Capture answer for the current question when a radio button is changed
captureAnswer();
});
});
Casey MacLeod is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.