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.

user3002293
  • 229
  • 3
  • 4
  • 13

1 Answers1

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)

Didier Sampaolo
  • 2,566
  • 4
  • 24
  • 34
Sterling Archer
  • 22,070
  • 18
  • 81
  • 118
  • 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. – user3002293 Nov 18 '13 at 21:04
  • 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 ? – user3002293 Nov 18 '13 at 21:30
  • You'd have to bind a function using `addEventListener()` to bind a function to a dynamic element – Sterling Archer Nov 18 '13 at 21:31
  • I know, sorry for asking again, but, how can I bind that to a dynamic element? – user3002293 Nov 18 '13 at 21:44