【问题标题】:JS->Form validation on inputs. Using for loop to get all the inputs indexJS->表单验证输入。使用 for 循环获取所有输入索引
【发布时间】:2016-07-06 20:34:47
【问题描述】:

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

在此之后,我在 JS 中创建了一个 for 循环来获取每个输入的索引并应用我的 if 语句来显示警报 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

如果你想看到显示 press Run with JS 的警报

谢谢!

【问题讨论】:

  • 请把相关的sn-ps代码贴在这里,不要仅仅作为jsbin.com的链接。

标签: javascript html forms validation


【解决方案1】:

我建议对您的 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;
}

Updated jsbin here

【讨论】:

  • 我已经使用了你的函数版本,如果条件不满足,我添加了一个小的 else 来隐藏我的警报。
【解决方案2】:

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

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

【讨论】:

  • 好的。我已经实施了您的更改,我可以看到这是如何工作的。此外,我已将 onsubmit 更改为 onchange 以保持警报显示。在我输入有效值后它们不会消失。
猜你喜欢
  • 2014-10-11
  • 1970-01-01
  • 2015-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-15
相关资源
最近更新 更多