form onSubmit return false doesn't work in Chrome

不想你离开。 提交于 2019-12-10 14:19:51

问题


My return false statement doens't work in Chrome when I want to check the user input through javasript. It fires the action tag even when I return false. Here's my code

<script type="text/javascript">
  function testInput(){
    if(document.getElementById("input1").value == ""){
      alert('error');
      return false;
    }else{
      return true;
    }
  }
</script>

The HTML

<form action="exec.php" method="post" onSubmit="return testInput()">
<input type="text" id="input1" name="input1" />
<input type="submit" value="Exec" />
</form>

回答1:


I know I'm late but this reply may help somebody in the future. I encountered the same issue today. After reading Jack's comment I inserted a try/catch block in my check function. This allowed me to prevent execution to stop (returns false even if the code crashes) and to print the error in the Chrome console panel. You can try the same like so :

function testInput(){
    try {
        if (document.getElementById("input1").value == "") {
            alert('error');
            return false;
        } else {
            return true;
        }   
    } catch (e) {
        console.error(e.message);
        return false;
    }
}



回答2:


Are you sure there is not blank spaces in the input field.

Try something like this if(document.getElementById("input1").value.trim() == "")

Please note that tirm will not work fine in IE. Use this work around if needed http://goo.gl/L802W



来源:https://stackoverflow.com/questions/10877135/form-onsubmit-return-false-doesnt-work-in-chrome

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!