Home > Software design >  JavaScript function works, but not when I try expanded its functionality
JavaScript function works, but not when I try expanded its functionality

Time:02-14

I have this simple form in my HTML code to upload a file, and a JavaScript function to make sure the file is not too large, everything works fine. In fact the second false in my JavaScript is there just to keep me from submitting the form while I build up the validation function.

My error starts to occur when I try to check if a file has not been selected.

Just using the code below, if I select no file, then click submit, the form posts and calls the second script. Even though my JavaScript function always returns a false.

I'm guessing that I have a JavaScript error, hence why my code jumps out of the function and the form continues posting.

Am assuming there's a proper way to call document.getElementById('myFile').files[0].name and check it for NULL, without triggering an error?

HTML Form

<form onsubmit="return checkFile()" 
name ="uploadlist" action="http://www.example.com/cgi-bin/upload2.pl"  
method="post" enctype="multipart/form-data">

And the JavaScript

<script>
    function checkFile(){
                        
    var fileName = document.getElementById('myFile').files[0].name;
    alert(fileName);
    var fileSize = document.getElementById('myFile').files[0].size;
    alert(fileSize);
    
    if( document.getElementById('myFile').files[0].size > 1000000) {
        alert ("File is too large");
        return false;
        }
    return false;
    }
</script>
</body>

CodePudding user response:

Try adding required attribute to your <input> field:

<input type='file' required />

Or check document.getElementById('myFile').files length, e.g

if (document.getElementById('myFile').files.length == 0) return false;

CodePudding user response:

You can add the required attribute to the <input> field, but that assumes the browser supports it. Your Javascript should check document.getElementById('myFile').files.length to determine whether a file was specified.

function checkFile(){
if ( document.getElementById('myFile').files.length ) {
    var fileName = document.getElementById('myFile').files[0].name;
    alert(fileName);
    var fileSize = document.getElementById('myFile').files[0].size;
    alert(fileSize);
    if( document.getElementById('myFile').files[0].size > 1000000) {
        alert ("File is too large");
        return false;
    }
} else {
    alert('No file selected.');
}
return false;
}
<form onsubmit="return checkFile()" 
name ="uploadlist" action="#"  
method="post" enctype="multipart/form-data">
<input type="file" name="myFile" id="myFile" required>
<button type="submit">Go</button>
</form>

  • Related