How To Use Javascript's AddEventListener() To Override An HTML Form's Default Submit() Behavior
Solution 1:
You need to receive the event in your handler function, and prevent the event from executing its default behavior. This applies to click
events, submit
events - really any event that's cancelable.
// using your example
submitButton.addEventListener('click', func, false);
// here's what func should look like
function func( event )
{
if ( event.preventDefault ) event.preventDefault();
event.returnValue = false;
// do whatever
}
Solution 2:
Shouldn't the handler be added as event listner for "submit" event?
It makes sense the "click" event handler returning false does not prevent default submit behavior, I think. It makes sense, kind of, that the form gets submitted to both targets.
edit: added second paragraph.
comment: And as Ken says the event listener should be added to the form and not the button.
edit 2: So I was wrong. You shouldn't use "return false;" but something like...
event.preventDefault ? event.preventDefault() : event.returnValue = false;
Solution 3:
EASY WAY: Set the forms onsubmit attribute to return false
<form onsubmit="return false;">
Now if it MUST be done through assigning of an event listener through javascript, then the answer given by Peter Bailey is ideal.
My form validator does exactly what your trying to do. Check out this example
http://murdog05.github.com/yui3-gallery/examples/json/beforeSubmitExample.html
And the code base
http://yuilibrary.com/gallery/show/formvalidator
You might find it handy.
Post a Comment for "How To Use Javascript's AddEventListener() To Override An HTML Form's Default Submit() Behavior"