Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript .innerHTML resets my <input type="file">

I have a problem concerning multiple file uploads in javascript. I am trying to create my own multiple file upload by dynamically adding inputs. This is all easy as pie, but the problem is that whenever I add a new , my previous input-fields of the type "file" get reset.

If I remove the last lines of code where I alter the innerHTML of my parent div, the values of my do not get reset. Does anyone know how this problem can be solved? The javascript code can be found below. Thanks in advance.

if(document.getElementById("upload_queue").innerHTML.indexOf(_item) == -1)
{
    var _row = "<tr id='queue_row_" + items_in_queue + "'>";
    _row += "<td>";
    _row += "<div class='remove_uploaded_image' onclick='remove_from_queue(" + items_in_queue + ")'></div>";
    _row += "</td>";
    _row += "<td>";
    _row += _item;
    _row += "</td>";
    _row += "</tr>";

    document.getElementById("upload_queue").innerHTML += _row;
    document.getElementById("upload_image_" + items_in_queue).style.display = "none";

    items_in_queue++;

    document.getElementById("uploader_holder").innerHTML += 
        '<input id="upload_image_' + items_in_queue + 
        '" name="upload_image_' + items_in_queue + '" accept="image/jpeg" type="file"' + 
        'onchange="add_to_upload_queue()" style="display: inline;" />';
}
like image 408
Michiel Standaert Avatar asked Oct 22 '25 05:10

Michiel Standaert


1 Answers

Yeah... you're going to want to use appendChild instead of modifying the inner HTML:

var myInput = document.createElement("INPUT");
// do stuff to my input

var myContainer = document.getElementById("uploader_holder");
myContainer.appendChild(myInput);

That's the general gist of what you have to do - let me know if you need somethign more specific, but it looks like you've got a good hold on JS already... You're going to want to do that in almost all cases rather than setting inner HTML... So, building your TR as well... you'll have to append the TD to the TR, you'll have to append the TD with your input, you'll have to append your targeted table with the TR, etc.

like image 90
Brian Avatar answered Oct 23 '25 19:10

Brian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!