Example of how to clear the value of an input type = file (actually a trick):
$().ready(function() {
list = $("[class^=f_clear_]");
if (list.length > 0) {
$.each (list, function(key, row) {
var arr = row.className.split("_");
var selector = "#f"+arr[2];
$(this).click(function(){
GenericInputFileCleaner(selector);
});
});
}
});
function GenericInputFileCleaner(selector){
var clone = $(selector).clone(true);
clone.insertAfter(selector);
$(selector).remove();
clone.attr("id", selector.substring(1));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script></head><body><formaction="tmp.php" method="post" enctype="multipart/form-data">
<input type="button" value="x" class="f_clear_1"> <input name="f[]" type="file" id="f1"><br>
<input type="button" value="x" class="f_clear_2"> <input name="f[]" type="file" id="f2"><br>
<input type="button" value="x" class="f_clear_3"> <input name="f[]" type="file" id="f3"><br>
<input type="submit" value="send">
</form>
</body>
</html>
The logic here is to clone the element you want to clean, add the clone right in front and then remove the original. Thus, the clone will have the% empty% attribute. At the end, the clone receives the same ID from the original. But this must be done after the original has been removed.
This is a simpler and safer way than trying to set the value
attribute:
document.getElementById("seu_id_do_input").value = "";
or Jquery
$("#seu_id_do_input").val("");
Both should work fine, but depending on the browser and version, may not work. The reason everyone should already know is to avoid manipulating the value
attribute with malicious data. However, there is no problem with deleting the attribute and all browsers could release it. But some browsers, perhaps by bug or lack of implementation, do not allow to modify anything, even to erase the value.
So a safer option is to clone, add the clone in the HTML body and remove the original.
I preferred to do with JQuery because it was more practical. The code would be larger and more susceptible to compatibility errors if you tried to invent something without the framework.
I found it unnecessary to comment on the code and explain in detail why it is so small, readable, easy to understand. The part that matters is the value
function. The rest is merely didactic. Adapt as appropriate.
The disadvantage is that you will obviously lose any events related to this element or that depend on it ( GenericInputFileCleaner()
, for example). But it can be "easily" solved by recreating such events if they exist.