我想清除我的表单中的文件输入。
我知道如何用同样的方法设置资源……但该方法不会擦除所选文件路径。
注意:我希望避免重新加载页面、重置表单或执行AJAX调用。
这可能吗?
我想清除我的表单中的文件输入。
我知道如何用同样的方法设置资源……但该方法不会擦除所选文件路径。
注意:我希望避免重新加载页面、重置表单或执行AJAX调用。
这可能吗?
当前回答
document.getElementById('your_input_id').value=''
编辑: 这个选项不能在IE和opera中运行,但似乎可以在firefox、safari和chrome中运行。
其他回答
document.getElementById('your_input_id').value=''
编辑: 这个选项不能在IE和opera中运行,但似乎可以在firefox、safari和chrome中运行。
你需要用新的文件输入替换它。 下面是如何用jQuery完成的:
var inputFile = $('input[type=field]');
inputFile.wrap('<div />');
当你需要清除输入字段时使用这一行(例如在某些事件上):
inputFile.parent().html( inputFile.parent().html() );
将该值设置为“并不适用于所有浏览器。
相反,尝试将值设置为null,如下所示:
document.getElementById('your_input_id').value= null;
编辑: 我得到了不允许JS设置文件输入的非常有效的安全原因,但是提供一个简单的机制来清除已经选择的输出似乎是合理的。我尝试使用空字符串,但它在所有浏览器中都不起作用,NULL在我尝试过的所有浏览器中都起作用(Opera, Chrome, FF, IE11+和Safari)。
编辑: 请注意,设置为NULL在所有浏览器上都有效,而设置为空字符串则不行。
输入。Value = null是一个工作方法,但是如果从onclick事件调用它,它只会触发输入的change事件。
解决方案是在需要重置输入时手动调用onchange处理程序。
function reset_input(input) {
$(input)[0].value = null;
input_change_handler();
}
function input_change_handler() {
// this happens when there's been a change in file selection
if ($(input)[0].files.length) {
// file(s) selected
} else {
// nothing is selected
}
}
$(input).on('change', input_change_handler);
将值设为null或像这样的空字符串' ',以清除单个输入元素的值 您可以使用HTML按钮使用<input type= " reset " >属性轻松重置所有表单值。 HTMLFormElement.reset()方法可以恢复表单元素的默认值。此方法的作用与单击表单控件相同。
清除整个输入字段,而不必手动删除整个东西,或者如果在输入字段中已经有一个用户不想要的预先建议的输入。可能有很多情况。
您可以将此作为一个实际示例来尝试
const fileInputElement = document.getElementById('file-input'); const formElement = document.getElementById('input-form'); // Method-1: Clear files // fileInputElement.value = ''; // Method-2: Clear files // fileInputElement.value = null; // Method-3: Clear files - on event listener fileInputElement.addEventListener('change', (event)=>{ // If the file did not meet certain condition event.target.value = ''; }); // Method-4: Clear or reset whole form formElement.addEventListener('submit', (event)=>{ // If ajax call is failed to make request event.target.reset(); // or // formElement.reset() }); .form{ display: flex; flex-direction: column; width: 80%; margin-left: 10%; } #file-input, .form-control{ margin-top: 1rem; } .form-control{ padding: 1em 0; } #file-input{ background: #ccccff; } #file-input::-webkit-file-upload-button { background: #000033; color: white; padding: 1em; } .button-group{ display: flex; justify-content: start; } .btn{ background: #004d4d; color: white; width: 4rem !important; margin-right: 10px; } <form id='input-form' class='form' > <input type='file' id='file-input' /> <input type='text' class='form-control' id='text-input' placeholder='your name' /> <div class='button-group'> <button type='reset' class='form-control btn' id='reset-form'>Reset</button> <button type='submit' class='form-control btn' id='submit-form'>Submit</button> </div> </form>