javascript - 不要验证 javascript 中的隐藏字段
问题描述
你好,我是 javascript 和所有这些 html 和东西的新手。我有以下来自 w3schools 的代码来验证输入字段。我有这样的 html 输入字段。
<div id="employed" style="display:none;">
<p><input placeholder="Name Of The Organization / Institution ..." name="organization"></p>
<p><input placeholder="Designation ..." name="desig"></p>
<p><input placeholder="Place Of Work ..." name="workplace"></p>
<p><input placeholder="Communication Address ..." name="cadd"></p>
<p><input placeholder="E_mail ID ..." name="offemail"></p>
<p><input placeholder="Contact Number ..." name="contact"></p>
</div>
当用户选择单选按钮时,我有一个显示隐藏字段的 javascript。但是,当我单击下一步时,即使字段被隐藏,它也会验证这些字段。用于验证的 javascript 是这样的。
function validateForm() {
// This function deals with validation of the form fields
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
// 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;
(y[i].style.display == "none")?valid = true: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
}
请我现在正在学习,我被困在这里。提前致谢!
解决方案
因为输入 dom 在您的文档中仍然可用,并且只是隐藏了。为了防止您的验证验证隐藏的输入。将您的代码更改为此。
function validateForm() {
// This function deals with validation of the form fields
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
// 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 == "" && y[i].parentElement.style.display != 'none') {
// add an "invalid" class to the field:
y[i].className += " invalid";
// and set the current valid status to false
//valid = false;
(y[i].style.display == "none")?valid = true: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
}
推荐阅读
- javascript - 打开引导模式单击自动生成的元素
- puppet - 在 Yaml 中使用来自 hiera 哈希的值
- python - 放大极坐标图
- javascript - 如何获取动态生成的表 td 输入值
- php - 部分获取有序行
- javascript - Chrome 控制台的执行方式是否与 Visual Studio Code 相同?
- python - Django TypeError:int() 参数必须不是“设置”
- c - 将结构转换为成员类型的指针
- javascript - 根据初始浏览器请求向服务器发送 JWT 令牌(使用本地存储)
- php - Codeigniter 上的未定义属性 PHP 错误