简体   繁体   中英

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 form s. 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

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> 

使用JavaScript,您可以执行以下操作。

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

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM