Reputation: 57373
I'm creating a simple web application with which a user may author a message with attached files.
multiple html file inputs with javascript link http://img38.imageshack.us/img38/4474/attachments.gif
That "attach additional files" link does not yet work. It should add an additional file input control to the form each time it's clicked.
I need a JavaScript method addanotherfileinput() to replace the clicked anchor:
<a href="#" id="attachlink" onclick="addanotherfileinput">attach additional files</a>
With this new table row, file input, and anchor:
<input type="file" name="Attachment1" id="Attachment1" class="textinput" />
</td>
</tr>
<tr>
<td></td>
<td>
<a href="#" id="attachlink" onclick="addanotherfileinput">attach additional files</a>
And also increment the number: Attachment2, Attachment3, Attachment4, etc.
How can I do this?
Upvotes: 0
Views: 249
Reputation: 10812
There might be a better way, but I did this client side by creating a set of HTML form elements and then hiding/showing the rows using JavaScript to update the CSS class.
EDIT: I'll leave this here as an alternate method but I like the idea of adding INPUT elements through the DOM better.
Upvotes: 1
Reputation: 1074969
You probably don't want to replace the anchor, just insert something in front of it.
I use Prototype for things like this, because it irons out a lot of browser inconsistencies, particularly around forms and tables.
Using Prototype, it would look something like this:
function insertFileField(element, index) {
element.insert({
before: "<input type='file' name='Attachment" + index + " class='textinput'>"
});
}
// And where you're hooking up your `a` element (`onclick` is very outdated,
// best to use unubtrustive JavaScript)
$('attachlink').observe('click', function(event) {
event.stop();
insertFileField(this, this.up('form').select('input[type=file]').length + 1);
});
...the bit at the end finds the form containing the link, finds out how many input
s of type file
there are, and adds one for the index.
There are other ways as well, via the Element
constructor provided by Prototype, but text works quite well (in fact, it's usually much faster).
It would be similar, though slightly different, with jQuery, MooTools, YUI, Glow, or any of the several other JavaScript frameworks.
Upvotes: 1
Reputation: 10333
You could use the DOM to dynamically insert the file inputs
var myTd = /* Get the td from the dom */
var myFile = document.createElement('INPUT');
myFile.type = 'file'
myFile.name = 'files' + i; // i is a var stored somewhere
i++;
myTd.appendChild(myFile);
OR you can use this
http://developer.yahoo.com/yui/examples/uploader/uploader-simple-button.html
Upvotes: 6