简体   繁体   English

代码片段不起作用

[英]Snippet of code not working

Below is a simplified snippet of code from a form validation script. 下面是表单验证脚本的简化代码片段。 It does not work... 这是行不通的...

When the form is submitted and the user has left "inputfield" empty, the first alert pops up. 提交表单并且用户将“inputfield”留空时,会弹出第一个警报。 After the user has entered something in "inputfield", the second alert pops up when the user clicks submit. 用户在“inputfield”中输入内容后,当用户单击“提交”时,会弹出第二个警报。

Afterwards, the script should return false and continue validation. 之后,脚本应返回false并继续验证。 I need both alerts to be included in the same else if. 我需要将两个警报包括在同一个其他内容中。 What am I doing wrong? 我究竟做错了什么? The alerts do not show and the form validation ignores this portion of code... 警报没有显示,表单验证忽略了这部分代码......

    } else if (myform.inputfield.value=="") {
    alert ('Please enter something in the text field!');
    }
    if (myform.inputfield.value!=="") {
    alert ('Thank you for entering something in the field!');
    return false;
    }

I agree rather use document.getElementById, or jQuery $('#input1').val() 我同意使用document.getElementById或jQuery $('#input1')。val()

 <script type="text/javascript">
    function validate() {
        if (document.getElementById('input1').value == "") {
            alert('Please enter something in the text field!');
        }
        if (document.getElementById('input2') !== "") {
            alert('Thank you for entering something in the field!');
            return false;
        }
    }
</script>
</head>
<body>
    <form onsubmit="return validate()">
        <input id="input1" />
        <input id="input2" />
        <input type="submit" value="OK" />
    </form>
</body>

You might have a return statement before the specified line of code? 您可能在指定的代码行之前有一个return语句?

Isn't it better to declare a flag and return the it as a result? 声明一个标志并返回它是不是更好? take the following sample into account: 考虑以下示例:

var validationResult = true;

...
} else if (myform.inputfield.value=="") {
   validationResult = false;
   alert ('Please enter something in the text field!');
}
if (myform.inputfield.value!=="") {
   alert ('Thank you for entering something in the field!');
   validationResult = false;
}

return validationResult;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM