[英]JavaScript Validate Select Box
我使用此解決方案制作了一個多步驟表單。 https://www.w3schools.com/howto/howto_js_form_steps.asp
唯一的區別是此表單中需要的幾個字段位於 select 框中,出於某種原因,我無法根據查找 select 選項值的值來觸發驗證處理程序。
我想檢查並確保表單中的指定字段不會返回空字符串,就像 validateForm() function 中的輸入字段一樣。
這是JS代碼。 我在標記中表單的每個部分都使用相同的“制表符”class。 只有腳本需要驗證處理。
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";
}
我的頭有點像 web。有人可以幫忙嗎?
謝謝:! :D
沒關系。 我已經想通了。 腦放屁!
我需要像輸入字段一樣遍歷 select 字段。
因此,創建一個變量並通過將變量的值分配給當前選項卡並獲取標簽名稱(選擇)來復制對輸入字段所做的操作,然后編寫一個 for 循環來檢查每個當前選項卡以查看是否有值通過。
像冠軍一樣工作!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.