jQuery on submit preventDefault() does not works

2019-08-28 14:41发布

问题:

I have html form with submit button and input='file' control:

<form action="/Profile/UploadFile" enctype="multipart/form-data" method="post" onsubmit="OnUploadSubmit(this)"> 

OnUploadSubmit function looks like this:

  if (e.files[0].size > 5000000) {
        $('#upload_error').css('display', 'block');
        $('#upload_error').text('The file size is too large for upload')
        e.preventDefault();
        return false;
    }

    var files = e.files;
    var ext = $('#file_uploader').val().split('.').pop().toLowerCase();
    if ($.inArray(ext, ['jpeg', 'jpg', 'png']) == -1) {
        $('#upload_error').css('display', 'block');
        $('#upload_error').text('Only, jpg, jpeg, png is allowed');
        e.preventDefault();
        return false;
    }
    return true;
}

e.preventDefault() and return false; doesnot working form is submiting anyway.

Does anybody knows what is my problem?

Thanks

回答1:

first you can't use preventDefault in this way because you not passed event object into function, and next:

onsubmit="return OnUploadSubmit(this)"

i Recommended:

add id attribute and remove onsubmit:

<form id="upload" action="/Profile/UploadFile" enctype="multipart/form-data" method="post"> 

jQuery:

$(function(){ // Document Ready

        $('#upload').submit(function(e){

        e.preventDefault();
         if (e.files[0].size > 5000000) {
                $('#upload_error').css('display', 'block');
                $('#upload_error').text('The file size is too large for upload')
            }

            var files = e.files;
            var ext = $('#file_uploader').val().split('.').pop().toLowerCase();
            if ($.inArray(ext, ['jpeg', 'jpg', 'png']) == -1) {
                $('#upload_error').css('display', 'block');
                $('#upload_error').text('Only, jpg, jpeg, png is allowed');
            }
        }

    });

});


回答2:

Does your method definition for OnUploadSubmit contain e as a parameter? If it does not, e.preventDefault will not work.



回答3:

Have you tried onsubmit="return OnUploadSubmit(this);" instead of onsubmit="OnUploadSubmit(this)"?



回答4:

I think you need onsubmit="return OnUploadSubmit(this)"