'what is the meaning of onsubmit="return false" ? why onsubmit="false" not working? what is the difference between them?
formValidation() function return false but not preventing form submission
<body>
<script>
function formValidation(){
return false;
}
</script>
<form onsubmit="formValidation()" method="POST" action="<?php echo $_SERVER['PHP_SELF'] ?>">
<label for="email">Email:</label><br>
<input type="email" name="email" id="email"><br><br>
<input type="submit" name="submit" value="submit">
</form>
</body>
When i have used return front of formValidation() function it is working
<body>
<script>
function formValidation(){
return false;
}
</script>
<form onsubmit="return formValidation()" method="POST" action="<?php echo $_SERVER['PHP_SELF'] ?>">
<label for="email">Email:</label><br>
<input type="email" name="email" id="email"><br><br>
<input type="submit" name="submit" value="submit">
</form>
</body>
Solution 1:[1]
Inline handlers like these essentially turn into a function body. Said function is executed when the event is fired.
function theHandler() {
// Attribute string goes here
}
If the function returns false, the event's default action (such as submitting the form) is prevented.
<form onsubmit="formValidation()"
doesn't work because then the constructed function that gets executed doesn't return anything:
function theHandler() {
formValidation()
}
But
<form onsubmit="return formValidation()"
works because then the constructed function is like
function theHandler() {
return formValidation()
}
It's somewhat confusing - and is one of the (many) reasons why you should never use inline handlers. Attach the event listener properly using JavaScript instead.
document.querySelector('form').addEventListener('submit', formValidation);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | CertainPerformance |
