How do i stop the form from reloading using Javascript?

后端 未结 5 1144
被撕碎了的回忆
被撕碎了的回忆 2020-12-01 15:18

When a User Submits the form i want to stop the default behavior of the form. ie it should not reload. so that i can perform the AJAX request.

here is the code i use

5条回答
  •  孤街浪徒
    2020-12-01 15:51

    You can use the onsubmit attribute as suggested, a more unobtrusive way is to use preventDefault() on the event object passed to the function bound to your onsubmit event:

    function validateForm(e) {
        if (e.preventDefault) {
           e.preventDefault();
        }
        e.returnValue = false; // for IE
    }
    

    This only works if you bind the event listener to the form, instead of having onsubmit inline.

    Edit: here's how you could bind an event listener to the form, which when triggered will pass an Event object (note this is the W3C style, this won't work in IE, but will give you an idea):

    var form = document.getElementById('myform');
    form.addEventListener('submit', validateForm, false);
    

    When the submit event is triggered, it will call the validateForm function, passing the event object. Here's a really good article on Javascript events:

    http://www.quirksmode.org/js/introevents.html

提交回复
热议问题