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