【发布时间】:2020-10-09 19:00:21
【问题描述】:
我使用此解决方案制作了一个多步骤表单。 https://www.w3schools.com/howto/howto_js_form_steps.asp
唯一的区别是此表单中所需的几个字段位于选择框中,由于某种原因,我无法根据查找选择选项值的值来触发验证处理程序。
我想检查并确保表单中的指定字段不会像 validateForm() 函数中的输入字段一样返回空字符串。
这里是 JS 代码。我在标记中表单的每个部分都使用相同的“选项卡”类。只是脚本需要进行验证处理。
var currentTab = 0; // Current tab is set to be the first tab (0)
showTab(currentTab); // Display the current tab
function showTab(n) {
// This function will display the specified tab of the form ...
var x = document.getElementsByClassName("tab");
x[n].style.display = "block";
// ... and fix the Previous/Next buttons:
if (n == 0) {
document.getElementById("nextBtn").style.display = "inline";
} else {
}
if (n == (x.length - 1)) {
document.getElementById("nextBtn").style.display = "none";
} else {
document.getElementById("nextBtn").innerHTML = "Next";
}
// ... and run a function that displays the correct step indicator:
fixStepIndicator(n)
}
function nextPrev(n) {
// This function will figure out which tab to display
var x = document.getElementsByClassName("tab");
// Exit the function if any field in the current tab is invalid:
// Hide the current tab:
x[currentTab].style.display = "none";
// Increase or decrease the current tab by 1:
currentTab = currentTab + n;
// if you have reached the end of the form... :
if (currentTab >= x.length) {
//...the form gets submitted:
document.getElementById("regForm").submit();
return false;
}
// Otherwise, display the correct tab:
showTab(currentTab);
}
function validateForm() {
// This function deals with validation of the form fields
var x, y, i, q, optCheck, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
q = x[currentTab].getElementById("required-select");
// A loop that checks every input field in the current tab:
for (i = 0; i < y.length; i++) {
// If a field is empty...
if (y[i].value == "") {
// add an "invalid" class to the field:
y[i].className += " invalid";
// and set the current valid status to false:
valid = false;
}
}
for(i = 0; q.length; i++){
optCheck = document.getElementsByTagName('option')[q][i].value;
if(optCheck.value == ""){
q[i].className += "invalid";
valid = false;
}
}
// If the valid status is true, mark the step as finished and valid:
if (valid) {
document.getElementsByClassName("step")[currentTab].className += " finish";
}
return valid; // return the valid status
}
function fixStepIndicator(n) {
// This function removes the "active" class of all steps...
var i, x = document.getElementsByClassName("step");
for (i = 0; i < x.length; i++) {
x[i].className = x[i].className.replace(" active", "");
}
//... and adds the "active" class to the current step:
x[n].className += " active";
}
我的脑袋有点像在网上。有人可以帮忙吗?
谢谢!! :D
【问题讨论】:
标签: javascript php html forms