how to reset element after addEventListener

Viewed 188

I have this code for client-side file size check on a file upload form (after which I have server side file size check too):

<script type='text/javascript'>
  document.getElementById('file_to_upload').addEventListener('change', checkFile, false);

  function checkFile(e) {
    var file_list = e.target.files;
    for (var i = 0, file; file = file_list[i]; i++) {
      if (file.size > <?php echo $max_file_size; ?>) {
        txt = "Your file is too big. Please keep files under " + (<?php echo $max_file_size; ?> / (1024 * 1024)).toFixed(1) + "Mb. Your file is " + (file.size / (1024 * 1024)).toFixed(1) + " Mb. \n";
      }
      alert(txt);
    }
  }
</script>

My problem is when I select a file larger than the allowed max size and I get the alert button, after that I cannot select a smaller file (if I do I keep getting the same error alert). How can I reset the listening event so it recalculates the next time a file is added?

thank you

2 Answers

You can reset your input field by this:

document.getElementById('file_to_upload').value = "";

Hope this will be helpful to you.

After further testing I realized the alert() needed to be inside the if statement or it would always trigger, no matter what the image size is, but I also implemented the suggestion above to reset the value of the file input otherwise it would maintain the value of the image that's too big, so the adjusted code is this:

<script type='text/javascript'>
    document.getElementById('file_to_upload').addEventListener('change', checkFile, false);
    function checkFile(e) {
        var file_list = e.target.files;
        for (var i = 0, file; file = file_list[i]; i++) {
            if( file.size > <?php echo $max_file_size; ?> ) {
                var txt = "Your file is too big. Please keep files under " + (<?php echo $max_file_size; ?> / (1024*1024)).toFixed(1) + "Mb. Your file is " + (file.size / (1024*1024)).toFixed(1) + " Mb. \n";
                alert(txt);
                document.getElementById('file_to_upload').value = "";
            }
        }
    }
</script>
Related