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

3

3 Answers 3

4

Using JavaScript you can do that as follows.

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

Sign up to request clarification or add additional context in comments.

3 Comments

@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 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.
document.getElementById("control").value = ""; there is a mistake in the answer '#' needs to be removed.
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>

5 Comments

This seems correct but it's not working in my script.
@isuru, do you have jQuery library included?
Yes. My JQuery version is v1.11.3. I think it is the issue.
@isuru, that shouldn't be the problem. I've made a fiddle just to check jsfiddle.net/y3rvmLx9 and it works. Somewhere else should be the problem.
Yes it should be worked. I cannot find the issue. However document.getElementById("#mcontrol").value = ""; solved the issue.
1
// For first file feild 
$("#clear").on("click", function () {

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

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

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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.