Js验证发送两个消息

js validation send both massage

本文关键字:两个 消息 验证 Js      更新时间:2023-09-26

我让HTML表单发送参数到JavaScript检查输入是否等于数组中的值,然后发送警报消息,但问题是当条件为真时函数发送两个警报

这是我的代码

<html>
<head>
    <title>TODO supply a title</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script type="text/javascript">
        function test(){
            var cars=["a","b","c"];
            var c;
            var inp=document.forms["form1"]["input1"].value;
            for(c=0;c<cars.length;++c){
                if(cars[c]===inp){
                    alert("we have it");
                }else{
                    alert("we don't have ");
                }
            }
        }
    </script>
</head>
<body>
    <form method="get" name="form1" onsubmit="return test()">
        <input type="text" name="input1" />
        <input type="submit" />
    </form>
</body>

我修改了两个警报"我们有它""我们没有"

这段代码有什么问题?

您需要更改逻辑,您需要查看它是否存在并查看所有逻辑。你不应该对每个索引都发出警告。

var inStock = false;  //Use a boolean to hold state
for(c=0;c<cars.length;++c){
    if(cars[c]===inp){  //see if it matches
        inStock = true;  //if it matches set Boolean to true
        break; //exit loop (no reason to keep looking)
    }
}
if(inStock) {  //check the boolean to see if we found it
  alert("we have it");
} else {
  alert("we don't have ");
}

在满足条件后添加一个return…

function test(){
        var cars=["a","b","c"];
        var c;
        var inp=document.forms["form1"]["input1"].value;
        for(c=0;c<cars.length;++c){
            if(cars[c]===inp){
                alert("we have it");
                return;
            }else{

                alert("we don't have ");
            }

        }
    }