如何使用JavaScript / jQuery重置input type =“file”
在本文中,我们将学习如何使用JavaScript / jQuery重置/清除input type =“file”。我们可以使用jQuery和HTML轻松重置文件。这也可以使用JavaScript和HTML完成。
方法:使用jQuery中的wrap方法: 重置input type = “file”的最佳方法是重置整个表单。将包裹在标签中并重置表单:
示例1: 在此示例中,我们将看到使用wrap方法。
<!DOCTYPE html>
<html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<!-- jQuery code to show the
working of this method -->
<script>
(document).ready(function () {
('#resetbtn').on('click', function (e) {
let el =('#infileid');
el.wrap('<form>').closest(
'form').get(0).reset();
el.unwrap();
});
});
</script>
</head>
<body>
<h2 style="color:green">GeeksforGeeks</h2>
<form id="find" name="formname">
<p>
<label>File</label>
<input id="infileid" type="file">
</p>
<p>
<button id="resetbtn" type="button">
Reset file
</button>
</p>
</form>
</body>
</html>
输出结果:

方法:使用file.value = ”:最简单的重置输入的方法是将填充值更改为无。这种方法在所有浏览器中都适用。
示例2: 在这个示例中,我们将看到使用 file.value = ‘ ‘
<!DOCTYPE html>
<html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<!-- jQuery code to show the
working of this method -->
<script>
function resetFile() {
const file =
document.querySelector('.file');
file.value = '';
}
</script>
</head>
<body>
<h2 style="color:green">
GeeksforGeeks
</h2>
<input type="file" class="file" />
<br>
<button onclick="resetFile()">
Reset file
</button>
</body>
</html>
输出:

方法:使用jQuery中的wrap方法: 将 <input type = “file"> 包裹在 <form> 标签中并重置表单:
示例3: 在这个示例中,我们将看到在jquery中使用 wrap方法的用法。
<!DOCTYPE html>
<html>
<body>
<h2 style="color:green">
GeeksforGeeks
</h2>
<form id="find"
name="formname">
<p>
<label>File</label>
<input type="file">
</p>
<p>
<button id="resetbtn"
type="button"
onClick="this.form.reset()">
Reset file
</button>
</p>
</form>
</body>
</html>
输出:

极客教程