views:

151

answers:

4

Hey everyone,

My knowledge of jquery isn't very vast but what I'm trying to do is allow a user to click a button on a form to add more fields to the form to be submitted to the form itself... Something similar to how gmail used to handle email attachments by adding a bunch of input fields for each file, anyone have some pointers on how to do that?

+2  A: 

Without writing all of the code for you, create a container, like a div inside your form.

<div id="morefields"></div>

Keep a global var with the # of fields

var fieldCount = 0;

Then add to the html of that div

fieldCount++;
var id = 'fieldname' + fieldCount;
var fields = $("#morefields").html() + "<input id='" + id + "' name = '" + id + "' />";
$("#morefields").html( fields);

have your controller function accept FormCollection as a parameter, read the fields.

There hopefully is a cleaner way which someone will post. This is how I've done it before. Code may not compile, written from memory, but you get the gist.

Russell Steen
The appendTo below looks cleaner.
Russell Steen
(+1) maybe I would just name the inputs like this: name='fieldname['+fieldCount']'; so ModelBinding can be used in controllers action.
Misha N.
A: 

Using jQuery,

Static Form Data

You can .show() and .hide() a DIV on a button click. This will let you toggle the displaying of your extra info DIV.

link

or

Dynamic Form Data Using .load(), you can dynamically load content from a file/the server and use .html() to add it into your form.

link

Write back with which one you want to do and I'll provide more info if you want.

Evildonald
dynamic, because i wont know how many items a user will want to add
Jimmy
+3  A: 

Given a button with id="buttonId" and a div where you want to put your new fields into with id="contentDiv":

$('#buttonId').click(
   function() {
      $('<div>someinput, like textboxes ecc</div>')
         .appendTo($('#contentDiv'));
   }
);

With this syntax you can operate on the new content directly, like:

$('#buttonId').click(
   function() {
      $('<div>someinput, like textboxes ecc</div>')
         .hide()
         .appendTo($('#contentDiv'))
         .fadeIn('fast');
   }
);

So the new content is faded in instead of just showed.

Alex Bagnolini
I forgot about appendTo, this looks much cleaner :)
Russell Steen
for some reason this isn't working on my page... syntax is the same, nothing happening on the page, everything being pulled in correctly not sure why it's having problems
Jimmy
Be sure to match all the IDs of the example (write it without sharp "#" in the tag, but be sure to put the "#" in the selector). Then, mMake sure you provide correct HTML content in the selector.
Alex Bagnolini
A: 

There's a plug-in for that :). See jquery-dynamic-form.

Jim Lamb