Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
188
rated 0 times [  193] [ 5]  / answers: 1 / hits: 20173  / 13 Years ago, tue, november 22, 2011, 12:00:00

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?


More From » forms

 Answers
17

I think your problem occurs because you are using the DOM Level 2 Event Registraton with addEventListener, so you can use event.preventDefault() for Firefox and event.returnValue=false to other browsers. Try with this demo:



http://jsfiddle.net/pYYSZ/42/


[#88959] Monday, November 21, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dannyc

Total Points: 517
Total Questions: 106
Total Answers: 116

Location: Netherlands
Member since Mon, Jun 7, 2021
3 Years ago
;