How do I 'unselect' a selected file?
Asked Answered
C

3

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?

Carburet answered 22/8, 2014 at 8:29 Comment(4)
possible duplicate of Clearing <input type='file' /> using jQueryStagemanage
The solution in the link does not work @farhatmihalkoDisregard
Thanks farhatmihalko. I was looking for an angular way of doing it. If there isn't, I can use this.Carburet
Indeed doesn't work on IE10 (works in IE11). Otherwise, see #1044457Cb
D
14

Simply clear the value of the file input element:

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

Here's a demo

Disregard answered 22/8, 2014 at 8:43 Comment(2)
@Carburet 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: https://mcmap.net/q/1600337/-how-do-i-39-unselect-39-a-selected-filePaugh
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 overheadDisregard
P
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.

Paugh answered 22/8, 2014 at 9:12 Comment(0)
B
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>
Bobbyebobbysocks answered 2/4, 2015 at 15:18 Comment(1)
OP asked question related to angularjs. How google lead you here?Chelseychelsie

© 2022 - 2024 — McMap. All rights reserved.