Forum Moderators: open
I've looked all over the web, and the only discussion about preventing form submissions (for error checking or whatever the reason) seems to be:
<form action="blah" onsubmit="return myFunction(this);">
However, I want a unobtrusive approach, and add the event using DOM event handlers instead. The problem is, when my function is called this way I don't know how to stop the form being submitted. Returning False achieves nothing.
Surely if there is a form.submit() function then there must be a way to cancel it.
If this is not possible then my hope of fully unobtrusive javascript is lost.
The problem is, when my function is called this way I don't know how to stop the form being submitted.
Here's a basic example of form validation and if it doesn't validate, the form isn't submitted:
<script type="text/javascript">
<!--
function validate(form)
{
for(i = 0; i < form.elements.length; i++)
{
if(form.elements[i].value == "") {
alert("Please fill out all fields!");
return false;
}
}
return true;
}
//-->
Then of course I have a form like this:
<form method="post" action="index.php" onSubmit="return validate(this);">
I'm thinking this answers your question of not knowing how to use the onSubmit return method? Anyway, hope this helps! :)
<form action="blah">
with no inline HTML event handlers, and then you use unobtrusive JavaScript to attach the event handler to the form.
The answer is that yes, this is possible. You need to stop the event from propagating. I've found that the easiest way to do this is using a platform library like the Yahoo UI Library [developer.yahoo.com] to handle events.
For example, using the YUI Event utility:
<script type="text/javascript" src="./yui/build/yahoo/yahoo.js"></script>
<script type="text/javascript" src="./yui/build/event/event.js"></script>
<script type="text/javascript" src="./yui/build/dom/dom.js"></script>
<script type="text/javascript">
function validate(e)
{
// Perform validation... if it fails, then call...
YAHOO.util.Event.stopEvent(e);
}
function attachBehaviors( )
{
YAHOO.util.Event.on('someForm','submit',validate);
}
YAHOO.util.Event.on(window,'load',attachBehaviors);
</script>
Hope that helps.
Sorry about that. I should really stay where I belong: PHP Forum ;)