views:

161

answers:

2

Hi Guys,

I have a code to add input fields dynamically in js. But the problem is if i add 3 fields or more and then browse a file(if the input field is file), the value of the field selected disappears. Can any one help

Heres my code

Thanks in advance. :)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script type="text/javascript">
<!-- Begin
/* This script and many more are available free online at
The JavaScript Source!! http://javascript.internet.com
Created by: Husay :: http://www.communitxt.net */

var arrInput = new Array(0);
 var arrInputValue = new Array(0);
fields = 1;
maxInput = 4;
function addInput() {
 //arrInput.push(createInput(arrInput.length));
 if(fields <= maxInput){
     fields +=1;
     arrInput.push(arrInput.length);
     //arrInputValue.push(arrInputValue.length);
     arrInputValue.push("");
     display();
 }
}

function display() {
 document.getElementById('parah').innerHTML="";
 for (intI=0;intI<arrInput.length;intI++) {
   document.getElementById('parah').innerHTML+=createInput(arrInput[intI], arrInputValue[intI]);
 }
}

function saveValue(intId,strValue) {
 arrInputValue[intId]=strValue;
}

function createInput(id,value) {
 return "<input type='file' id='test "+ id +"' onChange='javascript:saveValue("+ id +",this.value)' value='"+ value +"'><br>";
}

function deleteInput() {
 if (arrInput.length > 0) {
    fields -=1;
    arrInput.pop();
    arrInputValue.pop();
 }
 display();
}
// End -->
</script>
</head>

<body>
<a href="javascript:addInput()">Add more input field(s)</a><br>
<a href="javascript:deleteInput()">Remove field(s)</a><br>
<input type="file" /><br>
<input type="file" /><br>
<input type="file" /><br>
<p id="parah"></p>


</body>
</html>
A: 

getting file name from file input is disabled in IE8 and firefox3, check

MichalBE
Alright but the problem here is when I add extra 3 file input and then browse a file and then again i add a file input, the previously selected file inputs value will disappear. I got you for your point mentioned above user32167 but the problem here is completely different...:)
Neeraj
A: 

You need to make use of the ID and NAME attributes in both your HTML and JavaScript. Names will identify the file on the HTTP layer when the file is uploaded to the server, IDs will identify the HTML tag in the browser.

Why not use the jQuery Library for this? You could cut down all your code down probably 75%.

psudo javascript jquery

$(#add).click({$(#fields).append("<input .... ... .... >")});

And that's just to add the field on click.

Thats cool. Thanks for the idea.. :)
Neeraj