The problem is with these lines of code:
submit = document.getElementById("submit");
submit.addEventListener("click", validateForm(FoodOrder), false);
room = document.getElementById("room");
room.addEventListener("blur", checkRoom(FoodOrder.room), false);
validateForm(FoodOrder)
and checkRoom(FoodOrder.room)
execute those functions immediately. Whenever you have a function name followed by ()
, you are sending a command to Javascript to execute the function immediately. You then assign the result of that function as the event listener. Obviously this calculates the result of validateForm
and checkForm
when the page loads, and subsequently doesn't do anything useful.
What you want to do, of course, is execute those snippets of code only when the event is fired. To do this you need to pass an actual function to addEventListener
, as you do in the following line of code:
clock.addEventListener("mouseover", formClock, false);
But you need to pass parameters to the functions, which you can't do just by passing the name. So what to do? Well, you actually need to create another function which is run when the event is fired and which in turn calls the function you want with the appropriate parameters:
submit = document.getElementById("submit");
submit.addEventListener("click", function() {
validateForm(FoodOrder);
}, false);
room = document.getElementById("room");
room.addEventListener("blur", function() {
checkRoom(FoodOrder.room);
}, false);
You can see your code in action on jsFiddle, a good tool for testing and prototyping Javascript and HTML!
Note also one bit of your code which is bad practice:
setTimeout("formClock()",1000) ;
It is never a good idea to pass a string to setTimeout
. You can pass a function object:
setTimeout(formClock, 1000);