how to unselect files in html forms?
Asked Answered
B

1

10

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.

Barthel answered 18/11, 2013 at 20:55 Comment(1)
Before I post my answer, do you want to unselect both inputs, or one at a time?Jericajericho
J
16

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)

Jericajericho answered 18/11, 2013 at 21:2 Comment(4)
I don't wanna reset all the inputs. I just wanna reset the ones I want, that's why I put one button for each input.Barthel
very nice, but how can I change your javascript code to make it automatic? let's say, my real form is dynamic, maybe I just have one file input, or maybe I have 20. So do you know how to alter the javascript ?Barthel
You'd have to bind a function using addEventListener() to bind a function to a dynamic elementJericajericho
I know, sorry for asking again, but, how can I bind that to a dynamic element?Barthel

© 2022 - 2024 — McMap. All rights reserved.