how to unselect files in html forms?

user3002293 picture user3002293 · Nov 18, 2013 · Viewed 9.6k times · Source

I have a simple php file upload form, something like this:

<form action="upload_file.php" method="post" onsubmit="return validateForm()" enctype="multipart/form-data">
<label for="file">Files:</label>
<input type="file" name="file[]" id="file"><button type="button">Remove File</button>
<input type="file" name="file[]" id="file"><button type="button">Remove File</button>
<input type="submit" name="submit" value="Submit">
</form>

and I would like to add a function the Remove File button in order to unselect the selected file. Is that possible ?

Thanks for the help.

Answer

Sterling Archer picture Sterling Archer · Nov 18, 2013

You'll have to add IDs to make it easier, otherwise you'll be traversing nodes and you won't like that.

<form action="upload_file.php" method="post" onsubmit="return validateForm()" enctype="multipart/form-data">
    <label for="file">Files:</label>
    <input id="file1" type="file" name="file[]" />
    <button id="rmv1" type="button">Remove File</button>

    <input id="file2" type="file" name="file[]" />
    <button id="rmv2" type="button">Remove File</button>

    <input type="submit" name="submit" value="Submit">
</form>

Then add the javascript to restore default values:

document.getElementById('rmv1').onclick = function() { 
    var file = document.getElementById("file1");
    file.value = file.defaultValue;
}

(change rmv1 into rmv2 and file1 into file2 for the other button)