输入的JS->表单验证.使用for循环获取所有输入索引 [英] JS->Form validation on inputs. Using for loop to get all the inputs index

查看:48
本文介绍了输入的JS->表单验证.使用for循环获取所有输入索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a form with 4 inputs and I want to show an alert on submit. What I have done is that I have already created the warnings that goes under every input with display:none; in CSS.

此后,我在JS中创建了一个for循环以获取每个输入的索引,并应用我的if语句来显示警报if === null ||==="使用变量制作 querySelector("THE CLASS").style.display ="block";

After this I have created a for loop in JS to get the index of every input and apply my if statement of showing the the alert if === null || === "" using a variable to make the querySelector("THE CLASS").style.display="block";

在我的表单上,我也有这行

Also on my form I have this line

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

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

My problem is when I submit my form the only alert that is shown is the one under the Username and after it appears it also disappears because I think that the for loop goes to the next input.

让我知道是否还有其他需要澄清的地方.

Let me know if there is something more to clarify.

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

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

If you want to see the alert showing press Run with JS

谢谢!

推荐答案

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

I suggest a few modifications to your validare() function:

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

Add a flag indicating whether the whole form is valid, assume it's true until you find an input that is invalid. Return the value of this flag.

var isValid = true;

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

Capture your validation messages too so you can access them by index like your inputs:

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

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

When you find an invalid input, display the associated message and update the valid flag to 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

这篇关于输入的JS-&gt;表单验证.使用for循环获取所有输入索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆