Javascript 返回 false,警报不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12009848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 15:03:58  来源:igfitidea点击:

Javascript return false, alert not working

javascriptformsreturnhandleronsubmit

提问by cream

i'm trying to make sure certain fields are not left blank in my form. it seems simple enough but for some reason it's not working. The alert is not showing, and return false is not working (it continues to post blank entries into my database) please help, what am i doing wrong. thank you!

我正在努力确保我的表单中的某些字段没有留空。它看起来很简单,但由于某种原因它不起作用。警报未显示,并且 return false 不起作用(它继续将空白条目发布到我的数据库中)请帮助,我做错了什么。谢谢!

the script:

剧本:

function check(){
var name = getElementById('name');
var date = getElementById('date');
var pri = getElementById('pri');
var asapc = getElementById('asapc');
var asapn = getElementById('asapn');
var obr = getElementById('obr');
var obc = getElementById('obc');
var obn = getElementById('obn');
  if (name.value == "" || date.value == "" || pri.value == "not" || asapc.value == "" ||  asapn.value == "" || obr.value == "" || obc.value == "" || obn.value == "") {
    alert( "One or more fields were not filled out." );
    return false ; }
    return true;
 }

The code:

代码:

<FORM ACTION="step2.php" METHOD="POST" onsubmit="check();">
<!-- fields here -->
<INPUT TYPE="submit" VALUE="CONTINUE">

回答by Raab

access every element as document.getElementById...and in form tag write this onsubmit="return check();"instead if onsubmit="check();"

访问每个元素,document.getElementById...并在表单标签中写这个,onsubmit="return check();"如果onsubmit="check();"

回答by epascarello

You are missing return here:

你错过了这里的回报:

<FORM ACTION="step2.php" METHOD="POST" onsubmit="return check();">

回答by Gustonez

You are missing (document) this is the correct syntax:

您缺少(文档)这是正确的语法:

document.getElementById('id');


<script>
function check() {
var name = document.getElementById('name');
var date = document.getElementById('date');
  if (name.value == "" || date.value == "") {
        alert( "One or more fields were not filled out.");
        return false; 
    }
}
</script>

and getElementByID means by ID not my tagName

和 getElementByID 表示 ID 不是我的 tagName

<FORM ACTION="step2.php" METHOD="POST" onsubmit="return check();">
  <input name="name" type="text" value="" id="name">
  <input name="date" type="text" value="" id="date">
   .....etc..
  <INPUT TYPE="submit" VALUE="CONTINUE">
</FORM>