isuru
isuru

Reputation: 3565

How to clear files from <input type='file' /> using jQuery or JavaScript

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

Upvotes: 1

Views: 14281

Answers (3)

Bandara
Bandara

Reputation: 283

Using JavaScript you can do that as follows.

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

Upvotes: 4

Yaswanth
Yaswanth

Reputation: 69

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

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

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

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

Upvotes: 1

Ionut Necula
Ionut Necula

Reputation: 11462

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>

Upvotes: 2

Related Questions