3

I have and apex:inputFile tag where a user can input a filename to upload on a visualforce page. I have a javascript function which checks and alerts if a filesize is too large. After the Alert the inputfield stays filled with the file. How do I clear the input in javascript.

Visualforce

<apex:inputFile id="inputfile" value="{!newAtt.body}" filename="{!newAtt.name}"  onchange="checkFileSize(event)" />

Javascript

    <script>
        function checkFileSize(event) {
    if(event.target.files[0].size > 2**20*5) {
      alert('File must be less than 5Mb');
        //**Clear input**
    }
  }
        </script> 
5

You can pass the element id in the checkFileSize method, and then do your processing then

<apex:page controller="FileUploadController">

    <apex:inputFile id="inputfile" value="{!newAtt.body}" filename="{!newAtt.name}"  onchange="checkFileSize(event,id)" />

     <script>
    function checkFileSize(event , id ) {
    if(event.target.files[0].size > 2**20*5) {
        alert('File must be less than 5Mb');
        //**Clear input**
         document.getElementById(id).value ='';  
      }
   }
    </script> 
</apex:page>
  • Thanks for your answer, how can I make this work if the apex:input is between an apex repeat. For now it only works for the first input. How do I get the event inputfile? – Thomas Dec 31 '18 at 14:31
  • @Thomas updated code to support apex:reperat7 – Pranay Jaiswal Dec 31 '18 at 14:36

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.