event.preventDefault in IE 10

2019-02-23 00:53发布

问题:

I am submitting a form and I want to prevent the submit action until I do a few other actions like showing a progress bar for file uploads. I set up this code based on SO questions such as event.preventDefault() function not working in IE.

$(document).ready(function(){
    $("#fileform").submit(function(e){
        if(!e) e = window.event;
        if (e.preventDefault){
            // Firefox, Chrome
            e.preventDefault();
        }else{
            // Internet Explorer
            e.returnValue = false;
        }

        // other code
    }
}

Everything works fine in Firefox and Chrome; the submit action is prevented, the progress bar appears and then the form is submitted when I tell it to. However, in IE 10, the first condition of the if statement is executed and the form seems to be trying to submit (IE 10's submit bubbles show up). Why is the first condition being executed?

Does IE 10 support preventDefault() where IE 8 and 9 didn't? If so, how do I properly handle preventing the form submit action in IE 8, 9, 10 that won't interfere with Firefox, Chrome, Safari, etc...?

回答1:

Just do the below, jQuery has already done the cross browser job for you.

$("#fileform").submit(function(e){
   e.preventDefault();
   // other code
});


回答2:

Try also to put the following:

e.stopPropagation();

after

e.preventDefault();

http://api.jquery.com/event.preventDefault/

http://api.jquery.com/event.stopPropagation/

If you read: Stop form from submitting , Using Jquery

you'll see:

Becoz e.preventDefault() is not supported in IE. In IE it is e.returnValue = false

The modified code:

   $("#fileform").submit(function(e){
        if(!e) e = window.event;

         e.preventDefault();
         e.stopPropagation();

        // other code, do something here
        return true; // or false if something goes wrong
    }