PDA

View Full Version : Preventing / removing the standard event form a submit button



sdevic
01-08-2008, 12:06 PM
Hi,

I'm a newbie to DOM scripting and have run into a problem that was not able to solve with all my books and online sourcces :-(

So I hope someone could explain how to remove the standard event from a submit button, I mean how can I prevent the submit button from actually submitting something?

Here's what I've tried so far (simplified):

First I attach a new event to the submit button (using the "addEvent" - cross-browser workaround from Scott Andrew):

function submitHandler () {
submitBtn = document.getElementsByName(submitButtonName)[0];
addEvent(submitBtn,"click",alertbox,false);

Then I handle the click on the submit button with my function

function alertbox () {
alert("This is not allowed");
return false;
}

The code works just fine until the alert box pops up. But then after clicking "OK" in the alert box the form will still be submitted (what it should not) - but only in Firefox. IE7 does not submit the form and halts after the alert box, just how it's supposed to be.

I've been playing around with stopPropagation, preventDefault and a lot of functions that I found online, but I just can't get it to work - I just got the feeling that this is some kind of secret science. And I'm afraid I don't even know where do I have to put event removing part - I guess somewhere in the alertbox() function... ???

Can anyone enligten me on this, any tiny hint would be much appreciated!

Thanks a lot,
sdevic

sdevic
01-08-2008, 01:16 PM
Solved!
I found a function that stops bubbling and prevents the standard event for all browsers.

Here it is:
function stopDefault(e){
if (window.event && window.event.cancelBubble
&& window.event.returnValue){
window.event.cancelBubble = true;
window.event.returnValue = false;
return;
}
if (e && e.stopPropagation && e.preventDefault){
e.stopPropagation();
e.preventDefault();
}
}

This function needs to be called from within the event handling function then. Works great.

Thank you anyway ;-)

boogyman
01-08-2008, 01:19 PM
instead of using a submit type input, use a button?

sdevic
01-09-2008, 08:46 PM
of using a submit type input, use a button?
Unfortunately that's not possible because most forms utilize the standard submit button and the script has to be as generic as possible :cool:

emminar
01-10-2008, 04:57 AM
<input type="button" value="bla" onclick="alertstuff">

That wont submit the form. Than you could use javascript to submit the form when you want it to.