Search code examples
jqueryasp.net-mvcasp.net-mvc-5webgrid

Click event handler in webgrid not working


I am working in implementing CRUD operations with WebGrid. I followed the link CRUD_Webgrid.

Below is the code of WebGrid population

@{ 
WebGrid grid = new WebGrid(Model, ajaxUpdateContainerId: "ajaxgrid",
                           rowsPerPage: 30);
}
<div id="divmsg" style="color: green; font-weight: bold"></div>
<a href="#" class="add">Add New</a>
<br />
<br />
@grid.GetHtml(
    tableStyle: "webgrid-table",
    headerStyle: "webgrid-header",
    footerStyle: "webgrid-footer",
    alternatingRowStyle: "webgrid-alternating-row",
    selectedRowStyle: "webgrid-selected-row",
    rowStyle: "webgrid-row-style",
    htmlAttributes: new { id = "grid" },
    fillEmptyRows: false,
    mode: WebGridPagerModes.All,
    firstText: "<< First",
    previousText: "< Prev",
    nextText: "Next >",
    lastText: "Last >>",
    columns: new[] {
        grid.Column(header: "Date",format: @<span> <span id="spanDate_@item.ID">@item.Date.ToString("yyyy-MM-dd")</span>     @Html.TextBox("Name_"+(int)item.ID,(string)item.Date.ToString("yyyy-MM-dd"),new{@style="display:none", @class="date-picker"})</span>),
        grid.Column(header: "Team",format: @<span> <span id="spanTeam_@item.ID">@item.Team</span> @Html.TextBox("Team_"+(int)item.ID,(string)item.Team,new{@style="display:none"})</span>),
        grid.Column(header: "Name",format: @<span> <span id="spanName_@item.ID">@item.Name</span> @Html.TextBox("Name_"+(int)item.ID,(string)item.Name,new{@style="display:none"})</span>),
        grid.Column(header: "Emp ID",format: @<span> <span id="spanEmp_ID_@item.ID">@item.Emp_ID</span> @Html.TextBox("Emp_ID_"+(int)item.ID,(int?)item.Emp_ID,new{@style="display:none"})</span>),
        grid.Column(header: "Voucher Count",format: @<span> <span id="spanVoucher_Cnt_@item.ID">@item.Voucher_count</span> @Html.TextBox("Voucher_Count_"+(int)item.ID,(int?)item.Voucher_count,new{@style="display:none"})</span>),
        grid.Column(header: "INC Created",format: @<span> <span id="spanINC_Created_@item.ID">@item.INC_Created</span> @Html.TextBox("INC_created_"+(int)item.ID,(int?)item.INC_Created,new{@style="display:none"})</span>),
        grid.Column(header: "INC Updated",format: @<span> <span id="spanINC_Updated_@item.ID">@item.INC_Updated</span> @Html.TextBox("INC_Updated_"+(int)item.ID,(int?)item.INC_Updated,new{@style="display:none"})</span>),
        grid.Column(header: "INC_Closed",format: @<span> <span id="spanINC_Closed_@item.ID">@item.INC_Closed</span> @Html.TextBox("INC_Closed_"+(int)item.ID,(int?)item.INC_Closed,new{@style="display:none"})</span>),
        grid.Column(header: "Planned Leave",format: @<span> <span id="spanPlannedLeave_@item.ID">@item.PlannedLeave</span> @Html.TextBox("PlannedLeave_"+(int)item.ID,(int?)item.PlannedLeave,new{@style="display:none"})</span>),
        grid.Column(header: "Unplanned Leave",format: @<span> <span id="spanUnplannedLeave_@item.ID">@item.UnplannedLeave</span> @Html.TextBox("UnplannedLeave_"+(int)item.ID,(int?)item.UnplannedLeave,new{@style="display:none"})</span>),
        grid.Column(header: "Emergency Leave",format: @<span> <span id="spanEmergencyLeave_@item.ID">@item.EmergencyLeave</span> @Html.TextBox("EmergencyLeave_"+(int)item.ID,(int?)item.EmergencyLeave,new{@style="display:none"})</span>),
        grid.Column(header: "Available",format: @<span> <span id="spanAvailable_@item.ID">@item.Available</span> @Html.TextBox("Available_"+(int)item.ID,(int?)item.Available,new{@style="display:none"})</span>),
        grid.Column(header: "Error Critical",format: @<span> <span id="spanError_Critical_@item.ID">@item.Error_Critical</span> @Html.TextBox("Error_Critical_"+(int)item.ID,(int?)item.Error_Critical,new{@style="display:none"})</span>),
        grid.Column(header: "Error Significant",format: @<span> <span id="spanError_Significante_@item.ID">@item.Error_Significant</span> @Html.TextBox("Error_Significant_"+(int)item.ID,(int?)item.Error_Significant,new{@style="display:none"})</span>),
        grid.Column(header: "Error Standard",format: @<span> <span id="spanError_Standard_@item.ID">@item.Error_Standard</span> @Html.TextBox("Error_Standard_"+(int)item.ID,(int?)item.Error_Standard,new{@style="display:none"})</span>),
        grid.Column(header: "Action",format:@<text> <a href="#" id="Edit_@item.ID" class="edit">Edit</a><a href="#" id="Update_@item.ID" style="display:none" class="update">Update</a><a href="#" id="Cancel_@item.ID" style="display:none" class="cancel">Cancel</a><a href="#" id="Delete_@item.ID" class="delete">Delete</a></text>)
    })

Clicking the Add New link adds a new row to the WebGrid, below is the code

$(".add").on("click", function () {
    var existrow = $('.save').length;
    alert("existrow: " + existrow);
    if (existrow == 0) {
        var index = $("#grid tbody tr").length + 1;
        var Name = "Name_" + index;
        var Date = "Date_" + index;
        var Team = "Team_" + index;
        var Emp_ID = "Emp_ID_" + index;
        var Voucher_Count = "Voucher_Count_" + index;
        var INC_Created = "INC_Created_" + index;
        var INC_Updated = "INC_Updated_" + index;
        var INC_Closed = "INC_Closed_" + index;
        var PlannedLeave = "PlannedLeave_" + index;
        var UnplannedLeave = "UnplannedLeave_" + index;
        var EmergencyLeave = "EmergencyLeave_" + index;
        var Available = "Available_" + index;
        var Error_Critical = "Error_Critical_" + index;
        var Error_Significant = "Error_Significant_" + index;
        var Error_Standard = "Error_Standard_" + index;
        var Save = "Save_" + index;
        var Cancel = "Cancel_" + index;

        var tr = '<tr class="webgrid-row-style"><td class="date-picker"><span> <input id="' + Date + '" type="text" class="date-picker"/></span></td>' +
        '<td><span> <input id="' + Team + '" type="text" /></span></td>' +
        '<td><span> <input id="' + Name + '" type="text" /></span></td>' +
        '<td><span> <input id="' + Emp_ID + '" type="text" /></span></td>' +
        '<td><span> <input id="' + Voucher_Count + '" type="text" /></span></td>' +
        '<td><span> <input id="' + INC_Created + '" type="text" /></span></td>' +
        '<td><span> <input id="' + INC_Updated + '" type="text" /></span></td>' +
        '<td><span> <input id="' + INC_Closed + '" type="text" /></span></td>' +
        '<td><span> <input id="' + PlannedLeave + '" type="text" /></span></td>' +
        '<td><span> <input id="' + UnplannedLeave + '" type="text" /></span></td>' +
        '<td><span> <input id="' + EmergencyLeave + '" type="text" /></span></td>' +
        '<td><span> <input id="' + Available + '" type="text" /></span></td>' +
        '<td><span> <input id="' + Error_Critical + '" type="text" /></span></td>' +
        '<td><span> <input id="' + Error_Significant + '" type="text" /></span></td>' +
        '<td><span> <input id="' + Error_Standard + '" type="text" /></span></td>' +
        '<td> <a href="#" id="' + Save + '" class="save">Save</a><a href="#" id="' + Cancel + '" class="icancel">Cancel</a></td>' +
        '</tr>';

        $("#grid tbody").append(tr);
    }
    else {
        alert('First Save your previous record !!');
    }
});

Clicking the Save link inserts the data to database using the following code

$(".save").on("click", function () {
    alert("save clicked!!");
    var id = $("#grid tbody tr").length;
    alert("id: " + id);
    var Name = $("#Name_" + id).val();
    var Date = $("#Date_" + id).val();
    var Team = $("#Team_" + id).val();

    if (id != "") {
        $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            url: '@Url.Action("SaveData", "source_individual_data")',
            data: { "Date": Date, "Team": Team, "Name": Name },
            dataType: "json",
            beforeSend: function () { },
            success: function (data) {
                if (data.result == true) {
                    $("#divmsg").html("Record has been saved successfully !!");
                    setTimeout(function () { window.location.replace("WebGridCRUD"); }, 2000);
                }
                else {
                    alert('There is some error');
                }
            }
        });
    }
});

Issue: When I click the Save link on the dynamically added row, it does not trigger $(".save").on("click", function () { above and there are no errors. I tried placing the same Save link

<a href="#" id="' + Save + '" class="save">Save</a>

in the grid.column("Actions") and from there it works. Not sure what is the issue. Please help.


Solution

  • When you use the below syntax

    $(".save").on("click", function () {
        ...
        ...
    });
    

    The click event handler will only work on elements with class="save" that exist when the page is rendered, however it won't work on the dynamically added elements with class="save".

    You need to use event delegation to attach the click event handler on the dynamically added save link when you add a new row. Since you have this in the grid.GetHtml syntax

    @grid.GetHtml(
        ...
        ...
        htmlAttributes: new { id = "grid" }
    

    the generated <table> will have id="grid" attribute, so you can use grid as the id of the container of the save link. Change the click event handler syntax from this

    $(".save").on("click", function () {
        ...
        ...
    });
    

    to this

    $('#grid').on('click','.save', function() {
        ...
        ...
    });