Reputation: 441
I have a form which has an option to upload a file.
I have included a script to check if the file size is too big before the form is submitted and it works if the user is trying to upload a file greater than 2MB an alert shows, and if the file is less than 2MB the file is uploaded. I then use PHP to validate the form and process it into an email
However, if the user does not try to upload a file at all, the alert message still pops up, preventing the form from being submitted.
How can I allow the form to be submitted if the user does not want to include an upload file? My code is:
<script>
document.forms[0].addEventListener('submit', function( evt ) {
var file = document.getElementById('file').files[0];
if(file && file.size < 2097152) { // 2 MB (this size is in bytes)
//Submit form
} else {
//Prevent default and display error
alert("File is over 2Mb in size!");
evt.preventDefault();
}
}, false);
</script>
Many thanks in advance if anyone can help me find the answer.
Tog
Upvotes: 0
Views: 1730
Reputation: 675
Return true if no file selected
<script>
document.forms[0].addEventListener('submit', function( evt ) {
var file = document.getElementById('file').files[0];
if(!file)
return true;
if((file && file.size < 2097152)) { // 2 MB (this size is in bytes)
//Submit form
}
else
//Prevent default and display error
alert("File is over 2Mb in size!");
evt.preventDefault();
}
}, false);
</script>
Upvotes: 0
Reputation: 18987
How can I allow the form to be submitted if the user does not want to include an upload file?
You need to change your if logic to check the size and stop the form submit only if the file is present, And not always. Right now your code checks for a file all the time and if its not present it gets into the else block hence stopping your submit event.
I would suggest you to refactor your logic as below.
<script>
document.forms[0].addEventListener('submit', function( evt ) {
var file = document.getElementById('file').files[0];
if(file) // perform the size check only if a file is present.
{
if(file.size < 2097152) { // 2 MB (this size is in bytes)
//Submit form
} else {
//Prevent default and display error
alert("File is over 2Mb in size!");
evt.preventDefault();
}
}
}, false);
</script>
This logic submits the form when there is no file uploaded, And when there is a file uploaded it does a check to make sure the file is less than 2 MB.
Upvotes: 2