Dynamically Add Input Fields using Javascript

krishnandu

Skilled
Hey friends, I'm facing a problem while dynamically generating <input type="file">

Here is the peice of javascript I'm using...
<script language="javascript" type="text/javascript">
var num = 1;
function add(){
num++;
image.innerHTML = image.innerHTML +"
<input type='file' name='image[]'>";
}
</script>

And the HTML div I'm using is...

<div id="image">
<input type="file" name="image[]"/>
Add
</div>

Now the Problem is, whenever I click "Add", an input type="file" field gets generated but resets other input type="file" field in that div.

I mean, say I've selected a file and then click "Add", a new input field gets generated the existing one gets resetted.

What is the solution?? Please help.

BTW I was wondering what's the diff b/w this two??
language="javascript" and type="text/javascript"
 
Hello Krishnandu ,

Good day , first of all.

I also tried tweaking around the code you gave but to no gain . Its simply not working . The answer to why is it not working after some indepth googling is this , for a html element of input type='file' , the value field is 'read only' . It cannot be programmatically set by the client because of security reasons. Hence when you are trying to use 'image.innerHTML' to programmatically set the value its failing and not taking the value.

and to the next part , language = 'javascript' was used in old browsers before w3c came up with new guidelines. Its still supported in browsers but is DEPRECATED , the newer and better way to write code is to use type=text/javascript.

Hope that answers that buddy.
 
Back
Top