1

There are several <input type='file' /> fields in my file and there are no any html forms. I want to clear attached files from particular <input type='file' />. Not from the all fields. I have use $('input').val(""); but it clears all the <input type='file' /> fields. So how I clear the attached files from particular <input type='file' /> field?

var control = $("#mcontrol");

$("#clear").on("click", function() {
  $('input').val("");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="mcontrol" /><br>
<input type="file" id="mcontrol2" />
<button id="clear">Clear</button>

Here is the fiddle

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
isuru
  • 3,385
  • 4
  • 27
  • 62
  • 1
    Look here (using jquery): http://stackoverflow.com/questions/1043957/clearing-input-type-file-using-jquery – PaTT Jan 20 '17 at 09:06
  • 1
    also your fiddle, is missing a link to jQuery so it fails on the first `$` – Joel Harkes Jan 20 '17 at 09:07
  • 1
    Possible duplicate of [Clearing using jQuery](http://stackoverflow.com/questions/1043957/clearing-input-type-file-using-jquery) – AymDev Jan 20 '17 at 09:11

3 Answers3

4

Using JavaScript you can do that as follows.

document.getElementById("#control").value = "";

AshHimself
  • 4,024
  • 1
  • 21
  • 26
Bandara
  • 283
  • 2
  • 4
  • 17
  • @isuru, can you please explain how this is different from my answer if you say you have `jQuery` included? I think you either have the jQuery included incorrectly or you don't include it at all. This answer is the same as mine only pure JavaScript way. – Ionut Necula Jan 20 '17 at 09:26
  • @Ionut As I think it should be jQuery version problem. I tried with your answer but it returns `Uncaught TypeError: control.val is not a function at HTMLImageElement.img.onload` error. – isuru Jan 20 '17 at 09:35
  • `document.getElementById("control").value = "";` there is a mistake in the answer '#' needs to be removed. – 730wavy Dec 29 '22 at 01:26
2

You can use the id you already have set:

var control = $("#mcontrol");
$("#clear").on("click", function() {
  control.val("");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="mcontrol" />
<br>
<input type="file" id="mcontrol2" />
<button id="clear">Clear</button>
Ionut Necula
  • 11,107
  • 4
  • 45
  • 69
1
// For first file feild 
$("#clear").on("click", function () {

    $('#mcontrol1').val("");
});

// For second file feild 
$("#clear").on("click", function () {

    $('#mcontrol2').val("");
});
Yaswanth
  • 49
  • 1
  • 9
  • 1
    Please try to provide context with your answer. A standalone answer may solve a problem in this specific scenario, but an explanation may solve many future problems. Try to include what you think is causing the issue and why your answer will solve it. – Newd Jan 20 '17 at 15:00