javascript delete file on unlimited upload button

464 views Asked by At

thanks for the upcoming assistance, I am working on a uploader and trying to add a javascript delete link to each extra input field. I have one that adds a child.

here is a codepen: http://codepen.io/anon/pen/NPPmYP

What I am wanting to do is during creation of the extra input fields, Here is my code if anyone is able to help.

I also tried these methods and they didnt work

<script language="javascript">
<!--
function _add_more() {

    files.appendChild(document.createElement("br"));

    var del = document.createTextNode("Delete ");
    document.getElementById("files").appendChild(del);

    var extra = document.createElement('input');
    extra.type="file";
    extra.id="images[]";
    extra.name="images[]";
    extra.size="50";
    extra.accept="image/jpeg";
    document.getElementById("files").appendChild(extra);
}
</script>

I tried changing what I have for that line into

var del = document.createTextNode('<a href="javascript:_del_extra();">delete</a> ');

But it just showed it as text instead of making it a clickable link, I am really unsure on how to create the function to remove a child without effecting any others. Thank you for the upcoming support

1

There are 1 answers

5
Sam Greenhalgh On BEST ANSWER

You'll need to attach an event handler to the click of the delete link.

Something like this. (Updated as per comment)

<script language="javascript">
function _add_more() {

    var del = document.createElement("a");
    del.appendChild(document.createTextNode("Delete"));
    del.href="#"; // Apply link styling

    var extra = document.createElement('input');
    extra.type="file";
    extra.id="images[]";
    extra.name="images[]";
    extra.size="50";
    extra.accept="image/jpeg";

    var additionalFile = document.createElement('span');
    additionalFile.appendChild(document.createElement("br"));
    additionalFile.appendChild(del);
    additionalFile.appendChild(extra);

    document.getElementById("files").appendChild(additionalFile);

    del.addEventListener('click', function(event){
        additionalFile.parentElement.removeChild(additionalFile);
        event.preventDefault();
    });
}
</script>