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?

Share Improve this question edited Jan 7, 2023 at 14:28 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Feb 15, 2011 at 23:41 fredrikekelundfredrikekelund 2,0952 gold badges21 silver badges34 bronze badges 2
  • 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
Add a ment  | 

1 Answer 1

Reset to default 6

What 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