When I submit the form I got an alert message. When I accept the alert it will submit the form anyway. Returning false is ignored.
Onclick can not be used. I try with var x = document.forms["form"]["fname"].value;
and still same.
<form id="f" method="post" name="form" onsubmit="return validateForm();" action="#">
<input type="text" name="fname" id="test" />
<input type="submit" value="submit"/>
</form>
<script type="text/javascript">
function validateForm() {
var x = document.getElementById('test').value;
if (x == null || x == 0 || x == "0") {
alert("Stop");
return false;
}
}
</script>
return false stops a form from being submitted. For example the following form will not be submitted: <FORM> <INPUT TYPE="BUTTON" VALUE="Click Me"> </FORM> However the following form will: <FORM> <INPUT TYPE="SUBMIT" VALUE="Click Me"> </FORM>
Use the return value of the function to stop the execution of a form in JavaScript. False would return if the form fails to submit.
If it returns false, then the HREF will be ignored. This is why "return false;" is often included at the end of the code within an onclick handler. Save this answer.
Web Developers use 'return false' in different ways. During form submission, if a particular entry is unfilled, return false is used to prevent the submission of the form.
Instead of <input type="submit" value="submit"/>
use <input type="button" value="Submit" onclick='validateForm()'/>
.
In your JS:
<script type="text/javascript">
function validateForm() {
var x = document.getElementById('test').value;
if (x == null || x == 0 || x == "0") {
alert("Stop");
}
else
document.form.submit();
}
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With