我有一个多页重力表,有 4 个问题,每个问题都是多项选择单选按钮。我正在寻找一种将每个答案存储在数组中的方法,以便我可以在提交表单后使用该数组执行一些功能。
这是我最近尝试实现此目的的 JavaScript,但它不起作用。我对如何解决这个问题感到非常困惑,所以任何帮助将不胜感激。
// 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();
});
});
这是一个例子,我认为足以继续前进。
jQuery(document).ready(function ($) {
function handleFormSubmit(e) {
e.preventDefault();
var answers = [];
// We always have checked inputs here (even after the step changes, inputs remain checked)
var checkedInputs = $(this).find('.gfield--type-radio input:checked');
//After the previous/next/submission we update our answers
checkedInputs.each(function (index) {
var input = $(this);
answers.push({
'name': input.attr('name'),
'value': input.val()
});
});
// Allow the form submission to continue
this.submit();
}
// Be sure to replace with your form ID
$('#gform_1').on('submit', handleFormSubmit);
})
您还可以查看有关重力形式的文档。
如果您熟悉 PHP,这可能会有用:https://docs.gravityforms.com/gform_pre_submission/