JS->输入的表单验证.使用 for 循环获取所有输入索引

JS->Form validation on inputs. Using for loop to get all the inputs index

本文关键字:输入 获取 for 循环 索引 使用 验证 表单 JS-      更新时间:2023-09-26

我有一个包含 4 个输入的表单,我想在提交时显示警报。我所做的是我已经创建了带有 display:none 的每个输入下的警告;在 CSS 中。

在此之后,我在 JS 中创建了一个 for 循环来获取每个输入的索引并应用我的 if 语句,如果 === null || === "使用变量进行querySelector("THE CLASS").style.display="block";

同样在我的表格上,我有这一行

<form method="post" class="q-form" name="form" onsubmit="return validate()">

我的问题是当我提交表单时,唯一显示的警报是用户名下的警报,出现后它也消失了,因为我认为 for 循环转到下一个输入。

让我知道是否还有什么要澄清的。

这里有所有代码:https://jsbin.com/kazopahuga/1/edit?html,js,output

如果要查看显示的警报,请按"使用 JS 运行"

谢谢!

我建议对validare()函数进行一些修改:

添加一个标志,指示整个表单是否有效,假设它是真的,直到找到无效的输入。 返回此标志的值。

var isValid = true;

也捕获验证消息,以便您可以像输入一样按索引访问它们:

messages = document.getElementsByClassName(' alert alert-danger custom');

发现无效输入时,显示关联的消息并将有效标志更新为 false。

if (currentInputValue == null || currentInputValue === "") {
    messages[index].style.display = "block";
    isValid = false;
}

以下是更新的功能:

function validare() {
    var inputs, messages, index;
    var isValid = true;
    inputs = document.getElementsByTagName('input');
    messages = document.getElementsByClassName(' alert alert-danger custom');
    for (index = 0; index < inputs.length; ++index) {
        var currentInputValue = inputs[index].value;
        if (currentInputValue == null || currentInputValue === "") {
            messages[index].style.display = "block";
            isValid = false;
        }
    }
    return isValid;
}

在此处更新了 jsbin。

这是一个更新的解决方案: jsbin

你使用了querySelector,它只返回它找到的具有相同类的第一个元素,你应该使用querySelectorAll,它返回所有选择器。