最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - form onSubmit return false doesn't work in Chrome - Stack Overflow

programmeradmin3浏览0评论

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>

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>
Share Improve this question asked Jun 4, 2012 at 6:26 Joren WillemsJoren Willems 1671 gold badge6 silver badges12 bronze badges 6
  • it is working perfectly in g chrome – user1432124 Commented Jun 4, 2012 at 6:29
  • Yes the alert displays and the code works in IE and FF but not in Chrome – Joren Willems Commented Jun 4, 2012 at 6:39
  • 2 These issues tend to arise when a JavaScript error has occurred and the browser just stops evaluating more code. – Ja͢ck Commented Jun 4, 2012 at 6:40
  • Yes, but the strange thing is that it's work in IE and FF so I think there is nog JS error... – Joren Willems Commented Jun 4, 2012 at 6:44
  • if anyone of you have downvoted my answer then see there that there was no need to downvote – user1432124 Commented Jun 4, 2012 at 6:51
 |  Show 1 more ment

2 Answers 2

Reset to default 2

I know I'm late but this reply may help somebody in the future. I encountered the same issue today. After reading Jack's ment 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;
    }
}

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

发布评论

评论列表(0)

  1. 暂无评论