I could submit a form and validate it using a simple anonymous function in javascript as,
document.getElementById( myForm ).onsubmit = function() {
if(document.getElementById( email ).value == "") {
document.getElementById( errormessage ).innerHTML = "Please provide at least an email address";
return false;
} else {
return true; // Note this
}
};
In the example above using anonymous function, I could simply assign the return value when the document is submitted and prevent the page from being submitted while in the example below I use addEventListener
to add event when the form is submitted and it is further evaluated by validate function. I have also placed the return value to be true or false but this approach does not seem to work and the page gets submitted. I think I am wrong in returning the value
function addEventHandler(node, evt, func) {
if(node.addEventListener)
node.addEventListener(evt, func);
else
node.attachEvent("on" + evt, func);
}
function initializeAll() {
addEventHandler(document.getElementById( myform ), submit , validate);
}
function validate() {
if(document.getElementById( email ).value == ""){
document.getElementById("errormessage").innerHTML = "Please provide at least an email ";
return false;
} else {
return true;
}
}
addEventHandler(window, load , initializeAll);
How should I return value this way so as to prevent the form from submitting or submitting the form?