I've been trying to enhance my JavaScript ability, hence I'm attempting to submit a form with AJAX sans jQuery. And for some reason it seems impossible for me to use addEventListener();
to stop form submission with JavaScript.
window.addEventListener('load', function(){
document.forms[0].addEventListener('submit', function(){
send();
return false;
}, false);
}, false);
This code - independent of any way I attempt to swap order of the return false;
and the function call - will not stop the form from submitting, and neither will return send();
(returning false, naturally) or returnValue=false;
.
I'm able to stop the page from reloading and form from submitting the default way when using return false;
within an inline event listener, but should I have to use that? Any thoughts?
I've been trying to enhance my JavaScript ability, hence I'm attempting to submit a form with AJAX sans jQuery. And for some reason it seems impossible for me to use addEventListener();
to stop form submission with JavaScript.
window.addEventListener('load', function(){
document.forms[0].addEventListener('submit', function(){
send();
return false;
}, false);
}, false);
This code - independent of any way I attempt to swap order of the return false;
and the function call - will not stop the form from submitting, and neither will return send();
(returning false, naturally) or returnValue=false;
.
I'm able to stop the page from reloading and form from submitting the default way when using return false;
within an inline event listener, but should I have to use that? Any thoughts?
- Any reason why you can't use jQuery or another library? – ThiefMaster Commented Feb 18, 2011 at 14:30
- Well, in production, not really. But I just wanted to gain the understanding as to how for instance jQuery goes about acplishing this when it appears so difficult to do with native javascript... – fredrikekelund Commented Feb 18, 2011 at 14:44
1 Answer
Reset to default 6What browser are you using? addEventListener isn't supported in IE before IE 9.
Also, you have to run .preventDefault() and .stopPropagation().
And another thing, the load event won't fire before all of the contents of the page have loaded, including images and everything, so your handler may not be registered yet when you submit the form.
By the way, using jQuery it would be:
$(function(){
$('form').submit(function(){
send();
return false;
});
});
It would register the handler as soon as the DOM is ready and it would work in IE.