A Firefox Javascript bug?
I just came over a strange behaviour in Mozilla Firefox. It seems Firefox ignores return values for dynamically added event handlers. I stumbled upon this, when I tried to implement some quick mechanism to cancel a form submission.
The solution is well known and looks like this:
// The java script
function cancel()
{
return false;
}
// The form
<form onSubmit="return cancel()">
This works right away in any browser I tried.
However, this changes, if I attach cancel() dynamically, using addEventHandler() . This looks like this:
//The javascript
addEvent(window, "load", init);
function init()
{
form = document.getElementById("form1");
addEvent(form, "submit", cancel);
}
function cancel()
{
return false;
}
function addEvent(obj, evType, fn)
{
if (obj.addEventListener)
{
obj.addEventListener(evType, fn, false);
return true;
}
else if (obj.attachEvent)
{
var r = obj.attachEvent("on"+evType, fn);
return r;
}
else
{
return false;
}
}
//The form
<form id="form1">
While this behaves essentially like the first example in Internet Explorer, Firefox will submit the form whatever actually is returned by cancel(). I tried this on the most recent version 1.0.1. I prepared a test page, so you may have a look at the code and the behaviour yourself.
This is weird and seems to be a bug. Or did I get something wrong?
Update: I noticed there a quite a lot of people comming here from Google. Be welcome! The problem has been solved in the mean time, a solution can be found here.
Comment by Derek
November 3, 2005 - 00:28
Also worth noting is that submit events, whether in the onsubmit attribute or dynamically added, will not fire when form.submit(); is used. This is in IE and Firefox and I guess others.