View Full Version : add event and form submission for gecko browsers

10-18-2005, 10:03 PM
Ok, I will start off by saying that I have read quite a bit of JavaScript, but I have not had reason to practice with it very much.

I have a form validation script which has worked perfectly fine for me in the past. It was being attached to my form script using the popular addLoadEvent script using closures that has been popular across the net. Recently, I saw that the QuirksBlog contest for a better add/remove event listener (http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner.html) was over and decided to move to that script. I edited my code slightly (created an init script that is added when the page loads that adds the form validation script to my form element to be run when the form is submitted). This code runs perfectly fine in IE, but in Gecko browsers the script runs on submit, but then the page is also submitted (rendering the script useless). Does anyone have any idea why this may be happening? I tried using the DOM Inspector, but I don't see any of my scripts added to the form elements (should I?), no errors in the JavaScript console, but I have no idea how to use Venkman to debug this.

Here is my code:

Original idea by John Resig
Tweaked by Scott Andrew LePera, Dean Edwards and Peter-Paul Koch

Works in IE 5+, Mozilla, Opera, Safari. Does not work in NS4, MacIE.

function addEvent( obj, type, fn )
if (obj.addEventListener)
obj.addEventListener( type, fn, false );
else if (obj.attachEvent)
obj["e"+type+fn] = fn;
obj.attachEvent( "on"+type, obj["e"+type+fn] );

function removeEvent( obj, type, fn )
// Re-order if, else-if from Tweaked code to be consistent with above.
if (obj.removeEventListener)
obj.removeEventListener( type, fn, false );
else if (obj.detachEvent)
obj.detachEvent( "on"+type, obj["e"+type+fn] );
obj["e"+type+fn] = null;

// Validate fields on the client side first.

function formValidation() {
if (!(document.getElementById && document.getElementsByTagName)) return false;

var form = document.getElementById('contact');
var indexes = form.getElementsByTagName('input');
for (var i = 0; i < indexes.length; i++) {
if (indexes[i].type == 'text' && indexes[i].value.match(/^\s*$/)) {
indexes[i].value = '';
var id = indexes[i].id;
id = id.substring(0, 1).toUpperCase() + id.substring(1, id.length);
alert(id + ' field is empty.');
return false;

var from = document.getElementById('from').value;
if (!from.match(/^\s*\w+([\.-]\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})\s*$/)) {
alert('Invalid E-mail Address.');
return false;
return true;

function init() {
if (document.getElementById) {
var form = document.getElementById("contact");
addEvent(form, 'submit', formValidation);

addEvent(window, 'load', init);