问题
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