My Internet journey

One day son, this will all be yours…

Clearing an input of type=’file’

For obvious reasons, one cannot clear an input of type ‘file’ (in fact, the ‘value’ cannot be changed at all). Previous attempts to achieve this using setAttribute or direct access to the ‘value’ property has failed.
Our guys @ the UI team has found a useful workaround:

  1.  
  2. function resetUploadControl(control)
  3. {  
  4.     var parent = control.parentNode;
  5.     parent.removeChild(control);
  6.  
  7.     var tempForm = document.createElement("form");
  8.     tempForm.appendChild(control);
  9.     tempForm.reset();
  10.     tempForm.removeChild(control);
  11.     tempForm = null;
  12.    
  13.     parent.appendChild(control);
  14. }
  15.  

First, grab the elements’ parent, remove the control from it and append it to a temporary form. Input elements of type file can only be cleared by resetting the form they are part of, thus the temp form.
After resetting (and achieving our empty-valued input goal), re-append the control to its original parent and destroy the temp form. Mission accomplished! :)

Credit goes to Ori Roniger & Vadim Kononov

No comments