views:

28

answers:

2

I'm creating file(images) upload form. I want to add input elements by clicking on button.

This is my input:

<input type="file" name="file"/>

I've alerady write some code:

        <script language="javascript">
fields = 0;
function addInput() {
if (fields < 10) {
document.getElementById('text').innerHTML += "<input type="file" name="file"/><br />";
fields += 1;
} else {
document.getElementById('text').innerHTML += "<br />Only 10 upload fields allowed.";
document.form.add.disabled=true;
}
}
</script>

But it's ugly and not works...

I have prototype library and want to use it to add inputs.

So i need a button to add given inputs and on more button near every input to remove it - like when you attaching files to your mail.

+1  A: 

I think problem with use of "

document.getElementById('text').innerHTML += "<input type="file" name="file"/><br />";

should be

document.getElementById('text').innerHTML += "<input type='file' name='file'/><br />";

To remove field

 document.getElementById('text').innerHTML += "<div id='div_"+fields+"'><input type='file' name='file'/><br /><a onclick='removeDiv(/""+fields+"/")' href='javascript:void(0)'>Remove</a></div>";

and add javasript function

function removeDiv(val)
{
  var d = document.getElementById('text');
  var olddiv = document.getElementById("div_"+id);
  d.removeChild(olddiv);
  fields-=1; //this should be done to decrement count
}
Salil
ok, and what about removing inputs ?
Olexandr
input elements dont have a unique name
galambalazs
change name="file" to name="file[]"
Salil
+1  A: 

[See it in action]

HTML

<div id="text"></div>
<div id="warning"></div>

Javascript

fields = 0;

function addInput() {
  if (fields < 10) {
    var id = "file" + fields;
    document.getElementById('text').innerHTML +=
      "<div><input type='file' name='"+id+"' />" +
      " <a href='#' onclick='removeInput(this.parentNode)' />remove</div>";
    fields += 1;
  } else {
    document.getElementById('warning').innerHTML =
      "Only 10 upload fields allowed.";
    document.form.add.disabled = true;
  }
}

function removeInput( el ) {
  if (fields > 0) {
    document.getElementById('warning').innerHTML = "";
    var parent = document.getElementById('text');
    parent.removeChild(el);
    fields -= 1;
  }
}

​ ​

galambalazs