admin管理员组文章数量:1386693
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.
本文标签: javascriptDon39t reload page when submitting form without jQueryStack Overflow
版权声明:本文标题:javascript - Don't reload page when submitting form without jQuery - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744484622a2608376.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论