简体   繁体   中英

form onSubmit return false doesn't work in Chrome

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>

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;
    }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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