2013-11-25 27 views
1

我想從特定的輸入文件jQuery的 - 如何重置特定領域的重視

它如何,如果我有這樣的結構代碼來完成重置價值....

<div id="row_btnbar1" class="buttonbar"> 
    <div> 
     <div class="gallery"> 
      <output id="show_img1"></output> 
     </div> 
     <div class="button"> 
      <input type="file" id="files1" name="files[]"/> 
      <button id="reset1" type="reset" class="reset"> 
       <span>Reset</span> 
      </button> 
      <span class="process"></span> 
     </div> 
    </div> 
</div> 

<div id="row_btnbar2" class="buttonbar"> 
    // #files2, #reset2 
</div> 
<div id="row_btnbar3" class="buttonbar"> 
    // #files3, #reset3 
</div> 
<div id="row_btnbar4" class="buttonbar"> 
    // #files4, #reset4 
</div> 

回答

0

一個HTML文件輸入不能通過普通方式清除(即將值設置爲null或空字符串),但由於瀏覽器安全限制,大多數瀏覽器不允許這樣做。在許多瀏覽器中,設置一個空值屬性或者不起作用或者導致錯誤。相反,創建一個克隆舊元素並交換兩個元素的新元素。

閱讀:How to clear HTML file inputs


Trick:- You have to create new input type file and replace it with old one.


JS

function clearFileInput() { 
    var oldInput = document.getElementById("files1"); 
    var newInput = document.createElement("input"); 
    newInput.type = "file"; 
    newInput.id = oldInput.id; 
    newInput.name = oldInput.name; 
    newInput.className = oldInput.className; 
    newInput.style.cssText = oldInput.style.cssText; 
    // copy any other relevant attributes 
    oldInput.parentNode.replaceChild(newInput, oldInput); 
} 

fiddle Demo


OP的評論後更新

Updated fiddle Demo

$(document).ready(function() { 
    function clearFileInput(el) { 
     var oldInput = document.getElementById(el); 
     var newInput = document.createElement("input"); 
     newInput.type = "file"; 
     newInput.id = oldInput.id; 
     newInput.name = oldInput.name; 
     newInput.className = oldInput.className; 
     newInput.style.cssText = oldInput.style.cssText; 
     // copy any other relevant attributes 
     oldInput.parentNode.replaceChild(newInput, oldInput); 
    } 
    $('.reset').click(function() { 
     clearFileInput($(this).prev('input[type="file"]').attr('id')); 
    }); 
}); 
+0

這是完整的代碼預覽http://jsfiddle.net/7EVS4/1/,我想僅重置當前輸入文件填充。 – gierg

+0

@gierg檢查更新的答案。 –

+0

hwaa ....非常感謝...這是工作! :) thx ...;) – gierg