You are hereHome / Development / A Firefox Javascript bug?
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.


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.
// You can make the submit event fire when the form is submitted via a script (works only in FF):
var Event = document.createEvent('HTMLEvents');Event.initEvent('submit', false, false);
d.forms[0].dispatchEvent(Event);
[...] Firefox canceling problem solved I’d like to thank Johannes Hölzl, who pointed out my stupid mistake regarding canceling form sub [...]
The
ECMAScript binding for DOM Events says that the EventListener (which is the function "cancel") hasn't any returnvalue. But you get as parameter an Event object, where you can call "stopPropagation()" or "preventDefault()".