Clemzd
Clemzd

Reputation: 945

Why input file name disapear after adding a new one in javascript?

In Javascript, I automatically add a new input file each time I choose a file (jsfiddle).

<script>
    function addNewInputFile()
    {
        document.getElementById("inputs").innerHTML += '<input type="file" onchange="addNewInputFile()" />';
    }
</script>
<div id="inputs">
    <input type="file" onchange="addNewInputFile()" />
</div>

It's working except for the name of the file which disapears after the new input file has been appended. Do you know guys why the name disapear?

Upvotes: 0

Views: 51

Answers (1)

Ava
Ava

Reputation: 2429

When you use += on a string, it doesn't append to that string, it makes a new string that is the sum of both of the previous strings, then stores that in the original variable.

So, by doing this, you're actually clearing and then re-filling the innerHTML of #inputs, causing the DOM to refresh, and the two inputs that you see after it is completed to be two new inputs, therefore discarding any file you gave the previous input.

I would recommend using jQuery's append() or insertAfter() methods to add elements to that div instead.

Upvotes: 1

Related Questions