Zack Peterson
Zack Peterson

Reputation: 57373

How do I use jQuery to grow an HTML form?

I'm creating a simple web application with which a user may author a message with attached files.

multiple HTML file inputs with jQuery link http://img39.imageshack.us/img39/4474/attachments.gif

That "attach another file" link does not yet work. When clicked, it should add an additional table row and file input control to the form.

<tr id="fileinput0">
    <td>Attachments</td>
    <td>
        <input type="file" name="Attachment0" id="Attachment0" />
    </td>
</tr>
<tr id="fileinput1">
    <td></td>
    <td>
        <input type="file" name="Attachment1" id="Attachment1" />
    </td>
</tr>
<tr id="addinput">
    <td></td>
    <td>
        <a href="#">attach another file</a>
    </td>
</tr>

It should also increment the number: fileinput2, Attachment2; fileinput3, Attachment3; etc.

How can I do this with jQuery?

Upvotes: 0

Views: 763

Answers (5)

Zack Peterson
Zack Peterson

Reputation: 57373

I moved it around so it was all within a single table row:

<tr>
    <td>Attachments (<a id="addinput" href="#">add</a>)</td>
    <td id="fileinputs">
        <input type="file" name="Attachment0" id="Attachment0" />
    </td>
</tr>

And used this jQuery:

<script type="text/javascript">
    $(document).ready(function() {
        var num = 0;
        $("#addinput").click(function() {
            num++;
            $("#fileinputs").append("<br /><input type=\"file\" name=\"Attachment" + num + "\" id=\"Attachment" + num + "\" />");
        });
    });
</script>

It now looks like this:

multiple HTML file inputs with jQuery link http://img43.imageshack.us/img43/4474/attachments.gif

Upvotes: 1

ceejayoz
ceejayoz

Reputation: 180075

This'll get you most of the way there.

var row = $('table tr:last').clone();
$(row).attr('id', 'new_ID');
$('input', row).attr('id', 'new_ID_for_input');
$('table').append(row);

Upvotes: 4

Chris Thompson
Chris Thompson

Reputation: 35598

Keeping a counter might help, something like

$('form').append("<tr id=\"fileinput" + i + "\"><td></td><td><input type=\"file\" /></td></tr>");

Upvotes: 1

Joel
Joel

Reputation: 19368

I think something like this.

inputNum = 2;

function GrowTable()
{
    var input = $("<tr id=\"fileinput" + inputNum + "\">
        <td></td>
        <td>
            <input type=\"file\" name=\"Attachment" + inputNum + "\" id=\"Attachment" + inputNum + "\" />
        </td>
    </tr>");

    input.insertAfter("#fileinput" + (inputNum - 1));

    inputNum++;
}

Upvotes: 1

JMP
JMP

Reputation: 7844

You can create the HTML you want to append to the form and insert it into the appropriate container using jQuery.append().

Sometimes what I'll do is keep a TBODY in my form table and give that TBODY and ID so I can reference it via jQuery to append extra rows/cells/form inputs.

Upvotes: 3

Related Questions