Question

i want to reset value from specific input file

how it can be done if i have structure code like this....

<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>
Was it helpful?

Solution

An HTML file input can't be cleared by normal means (i.e. setting the value to null or an empty string), but because of browser security restrictions, most browsers don't allow this. In many browsers, setting a null value attribute either will have no effect or cause an error. Instead, create a new element that clones the old element and swap the two.

Read : 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


Updated after OP's comment

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'));
    });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top