0

I want to add input (type file) field to my html using js. I've got it done, but the problem is when the user chooses a file then clicks on the "new file" button to choose another one, The prevoius choosen file goes away and says no file chosen. what is the problem?

function newfile(){
    var divv=document.getElementById("files");
    var name="files"+divv.childNodes.length;
    divv.innerHTML+='<div><input id="'+name+'" name="'+name+'" type="file" accept="*" class="col-lg-11 col-md-10 col-sm-10 col-sx-6"></div>';
}
<div class="col-sm-10">
<div id="files"></div>
<a class="btn btn-primary col-sx-12" onclick="newfile()">New file</a>
</div>

1
  • You need to use appendChild() instead of innerhtml Commented Aug 3, 2017 at 4:58

1 Answer 1

1

This happens because everytime you use divv.innerHTML+='<div><input id="'+name+'" name="'+name+'" type="file" accept="*" class="col-lg-11 col-md-10 col-sm-10 col-sx-6"></div>' all contents in divv are replaced with new contents and the previous information is lost. you can use appendChild() here, something like this:

function newfile(){
var divv=document.getElementById("files");
var name="files"+divv.childNodes.length;
var inputNode = document.createElement("input");
inputNode.id = name;
inputNode.name = name;
inputNode.type = 'file';
divv.appendChild(inputNode);
}
<div class="col-sm-10">
<div id="files"></div>
<a class="btn btn-primary col-sx-12" onclick="newfile()">New file</a>
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.