ASP.NET MVC Ajax expandable form using jquery
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 hav开发者_C百科e some pointers on how to do that?
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.
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.
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.
There's a plug-in for that :). See jquery-dynamic-form.
精彩评论