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
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');
}
}
});
});
Does your method definition for OnUploadSubmit contain e as a parameter? If it does not, e.preventDefault will not work.
Have you tried onsubmit="return OnUploadSubmit(this);"
instead of onsubmit="OnUploadSubmit(this)"
?
I think you need onsubmit="return OnUploadSubmit(this)"