清空file input框

看風景就發表於2016-01-17

測試環境:
OS --> winXP
Browsers --> IE6+, FF 3.0.11, FF 3.5, Opera 9.64, Opera 10 beta 2, Safari 4, Chrome 2.0.172

xhtml:
<input type="file" value="選擇檔案" id="fileInput" />
<button type="button" id="btnClear">清空檔案域</button>

JS:
<script type="text/javascript">
var btn = document.getElementById("btnClear");
var file = document.getElementById("fileInput");
btn.onclick = function() {
  // for IE, Opera, Safari, Chrome
  if (file.outerHTML) {
    file.outerHTML = file.outerHTML;
  } else { // FF(包括3.5)
    file.value = "";
  }
}
</script>

或者

var file = $("#file")
file.after(file.clone().val(""));
file.remove();

參考: http://blog.163.com/thinker_creator/blog/static/101933149200961585128272/
    http://www.jb51.net/article/35491.htm

相關文章