Dynamically adding and removing form using jquery

Hi every one welcome again.It took me long to post on this blog.But i hope this article is very helpful for web developers.
In this article i will get to know about How to create,remove and save dynamically created form like picture above.This task is purely based on JQuery scripting.But,i you will easily understand the code using comments i wrote.And i will share my source code also..
1.Create Visual studio solution Web solution(Using ASP.NET MVC template).If you do not know how to create solution refer link: creating-first-application-in-aspnet-mvc.
2.Add a Controller to the solution.
3.Now in controller i prepared a Data source for drop down list and sent that data to view using ViewBag .
public class HomeController : Controller
        // GET: Home
        public ActionResult Index()
            //preparing dropdownlist data..
            List _ddllist = new List()
                new SelectListItem { Text = "Select", Value = "Select" },
                new SelectListItem { Text = "Student", Value = "Student" },
                new SelectListItem { Text = "Professor", Value = "Professor" },
                new SelectListItem { Text = "Volunteer", Value = "Volunteer" },
                new SelectListItem { Text = "Organizer", Value = "Organizer" }
            //sending using ViewBag..
            ViewBag.RegisterTypes = _ddllist;
            return View();
1.Add a  view by right clicking on Index controller.
2.Add Jquery and Jquery UI library file in _Layout page or View page created.
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<link href="~/Content/jquery-ui/theme/jquery-ui.1.11.1.css" rel="stylesheet" />
<script src="~/Scripts/jquery-ui-1.10.0.min.js"></script>

1.Now create view with below code.Here, i am not giving any explanation about how to write code but,you can easily understand by seeing code with documentation comments.

    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<link href="~/Content/jquery-ui/theme/jquery-ui.1.11.1.css" rel="stylesheet" />
<script src="~/Scripts/jquery-ui-1.10.0.min.js"></script>

@using (Html.BeginForm("", "", FormMethod.Post, new { id = "frmEventAttFee" }))
    <div id="DivAddFeeDetails" style="display:block;margin-top:50px;">
        <table id="tblEventAttendeeFee">
                    <td><span style="width:100px;">Reg Types</span></td>
                    <td><span style="width:70px;">Start Date</span></td>
                    <td><span style="width:70px;">End Date</span></td>
                    <td><span style="width:50px;">Seats Avilable</span></td>
                    <td><span style="width:70px;">Amount</span></td>
                    <td><span style="width:70px;">CodeRequired</span></td>
                    <td><span style="width:70px;">Amount</span></td>
                        @Html.DropDownList("ddlRegTypes_0", ViewBag.RegisterTypes as List<SelectListItem>, new { style = "width:100px",@class="form-control" })
                    <td><input class="form-control" style="width:70px;" id="txtRegStartDate_0" type="text" /></td>
                    <td><input class="form-control" style="width:70px;" id="txtRegEndDate_0" type="text" /></td>
                    <td><input class="form-control" style="width:50px;" id="txtNoOfSeatsAvilable_0" type="text" /></td>
                    <td><input class="form-control" style="width:70px;" id="txtAmount_0" type="text" /></td>
                    <td><input class="form-control" type="checkbox" id="chkPromotionCode_0" /></td>
                    <td><input class="btn btn-primary" type="button" id="btnAddNew" value="Add New" /></td>
    <hr />

    <input type="button" class="btn btn-success btn-lg" id="btnSubmit" name="btnSubmit" value="Submit" />
    <input type="hidden" id="hdnCountOfRows" name="hdnCountOfRows" />

<script type="text/javascript">

        $(document).ready(function () {
        //getting the checkbox value
        if ($("#chkPromotionCode_0").is(':checked')) {
            $("#chkPromotionCode_0").attr('checked', false);
        //initializing date pickers.
        var count = 1;
            //creating dynamic new form when click on 'Add New' button
            //and appending to table
        $("#btnAddNew").on("click", function () {
            $("#tblEventAttendeeFee").append('<tr id="row_'+count+'">'
            + '<td><select class="form-control" style="width:100px;" id="ddlRegTypes_' + count + '" name="ddlRegType_' + count + '"/></select></td>'
            + '<td><input class="form-control" style="width:70px;" type="text" id="txtRegStartDate_' + count + '" name="txtRegStartDate_' + count + '"/></td>'
            + '<td><input class="form-control" style="width:70px;" type="text" id="txtRegEndDate_' + count + '" name="txtRegEndDate_' + count + '"/></td>'
            + '<td><input class="form-control" style="width:50px;" type="text" id="txtNoOfSeatsAvilable_' + count + '" name="txtNoOfSeatsAvilable_' + count + '"/></td>'
            + '<td><input class="form-control" style="width:70px;" type="text" id="txtAmount_' + count + '" name="txtAmount_' + count + '"/></td>'
            + '<td><input class="form-control" type="checkbox" id="chkPromotionCode_' + count + '" /></td>'
            + '<td><input class="btn-remove btn btn-danger" type="button" id="' + count + '" name="' + count + '" value="Remove" /></td>'
            + '</tr>');

            //copying dropdown list data to a variable
            var ddldata = $("#ddlRegTypes_0").html();
            //appending dropdownlist data to dynamically created Dropdownlist
            $("#ddlRegTypes_" + count + "").append(ddldata);
            //initializing dynamically created datepickers

        //Removing dynamic form when click on remove button.
        $(document).on("click", ".btn-remove", function () {
            count=count - 1;
            var button_id = $(this).attr("id");
            $("#row_" + button_id + "").remove();

    //Saving data ww entered to a javascript list 
    $("#btnSubmit").unbind().click(function () {
        var DataList = [];
        var count = $("#hdnCountOfRows").val();
        for (var i = 0; i < count; i++) {
            if ($("#chkPromotionCode_" + i).prop('checked') == true) {
                $("#chkPromotionCode_" + i).val(true);
            else {
                $("#chkPromotionCode_" + i).val(false);
            if ($("#ddlRegTypes_" + i).val() && $("#txtRegStartDate_" + i).val() && $("#txtRegEndDate_" + i).val() && $("#txtNoOfSeatsAvilable_" + i).val() && $("#txtAmount_" + i).val())
                DataList.push({ RegisterTypeCode: $("#ddlRegTypes_" + i).val(), RegStartDate: $("#txtRegStartDate_" + i).val(), RegEndDate: $("#txtRegEndDate_" + i).val(), NoOfSeatsAvilable: $("#txtNoOfSeatsAvilable_" + i).val(), Amount: $("#txtAmount_" + i).val(), PromotionCodeRequired: $("#chkPromotionCode_" + i).val()});
        if ((DataList != null && DataList.length == 0) || DataList == null) {
            alert('please select RegType, Start date, End date, No of seats avilable and Amount for atlease one entry ');
            return false;
        else {
            //displaying list data in alert box
            //We can send data to Controller using ajax
        DataList = JSON.stringify({ 'DataList': DataList });
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            type: 'POST',
            url: 'AddEventAttendeeFee',
            data: DataList
        }).done(function (Result) {
            if (Result == true) {
                alert("Records Inserted successfully");
                var eventid = $("#hdnEventID").val();
                document.forms[0].action = "@Url.Action("EventFeeLookup", "Admin")?eventid=" + eventid;
        }).error(function (Result) {
            alert("Insertion failed");

1.If your form contains more fields(ex:above 10 fields) it is recommend to create dynamic form by taking a Partial View.because it is not recommend in coding standards.
2.Finally after clicking submit button saved data will come in alert box for two rows like below.

3.Download source code for this application from here.. Download.

I hope this tutorial will help you .To get more updates please subscribe to this blog subscribe. OR follow on Social networks for daily awesome updates[Facebook,twitter,google plus].
Dynamically adding and removing form using jquery Dynamically adding and removing form using jquery Reviewed by raviteja swayampu on 23:42:00 Rating: 5

No comments: