So I’ve condensed my problem into a snippet of HTML code for you guys to try out on your own.
I believe this was working in Firefox 3.6 but in more recent releases it no longer seems to work. It also doesn’t work in IE9 or Firefox Nightly.
<html>
<head>
<title>Test</title>
</head>
<script type="text/javascript">
function newEvent() {
var myEvent = document.createEvent("MouseEvents");
myEvent.initEvent("click", false, false);
getElementById('Test').dispatchEvent(myEvent);
}
</script>
<body>
<form action="" onSubmit="newEvent();return false;">
<input name="OK" type="submit" value="OK" />
<input id="Test" name="Test" type="button" onClick="alert('Success!');" value="Test" />
</form>
</body>
</html>
The problem I’m getting is that the form is being submit to the page, when I don’t want it to be. I’ve tried “return false;”, I’ve tried “event.preventDefault();”. If you comment the dispatchEvent line, everything else works as expected. I’m lead to believe that for some reason dispatching a new event (the click) seems to allow the onSubmit event to continue.
You can test yourself by clicking “OK”, which should fire onSubmit. Expected behaviour would be that a click event is generated for the “Test” button, then the onSubmit event is cancelled by the “return false;” section.
Any insight would be greatly appreciated.
You are missing something in your code:
See the third line:
http://jsfiddle.net/csrn5/2/
In
newEvent(), the third line needsdocument.. So what’s happening is you’re getting an error and that error is stopping the JS before it gets to thereturn false.Another way of demonstrating the problem:
http://jsfiddle.net/csrn5/4/
Note, fix the error, I just wanted to show you that that was the actual problem.