6

I'm using this to allow the user to select and upload a file:

<input id="fileInput" type="file" ng-file-select="onFileSelect($files)">

This correctly show:

enter image description here

When user clicks 'Upload', I upload the file.

When the user clicks 'Remove', how do I clear out the file name?

Jason
  • 1,787
  • 4
  • 29
  • 46
  • 2
    possible duplicate of [Clearing using jQuery](http://stackoverflow.com/questions/1043957/clearing-input-type-file-using-jquery) – Farkhat Mikhalko Aug 22 '14 at 08:31
  • The solution in the link does not work @farhatmihalko – raam86 Aug 22 '14 at 08:43
  • Thanks farhatmihalko. I was looking for an angular way of doing it. If there isn't, I can use this. – Jason Aug 22 '14 at 08:44
  • Indeed doesn't work on IE10 (works in IE11). Otherwise, see http://stackoverflow.com/questions/1043957/clearing-input-type-file-using-jquery – PhiLho Dec 01 '15 at 12:39

3 Answers3

14

Simply clear the value of the file input element:

document.getElementById('remove').addEventListener('click', function () {
    document.getElementById('fileInput').value = ''
});

Here's a demo

raam86
  • 6,785
  • 2
  • 31
  • 46
  • @Jason this is not an angular way, in angular you should not touch the dom elements directly this way. instead you can use `angular.element()` with use of `jqLite` event binding, see the answer below: http://stackoverflow.com/a/25443443/1059101 – Jai Aug 22 '14 at 09:27
  • Hi Jai, why isn't this the angular way? they do offer an api for dom manipulation buy why use it. You should that the same happens behind the scenes with less overhead – raam86 Aug 22 '14 at 09:39
5

It should be more angular way like this with angular.element(element):

angular.element(document.getElementById('remove')).on('click', function(){
    angular.element(document.getElementById('fileInput')).val('');
});

Plunkr Demo


From the docs usage:

angular.element(element);

where angular.element() creates a jQuery object and this (element) in the braces is the HTML string or DOMElement to be wrapped into jQuery.

Jai
  • 74,255
  • 12
  • 74
  • 103
0

Googling lead me here, so to help others you can also do this using straight jQuery:

$("#clear").on("click", function() {
  $("#fileInput").val("");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="fileInput" />
<button id="clear">Clear</button>
grg
  • 5,023
  • 3
  • 34
  • 50