Delete a row from a table and update other row values in javascript

Last Reply 5 hours ago By PrinceG

Posted 6 days ago

 

  var _nextId = 1;

    // ID of Product currently editing
        var _activeId = 0;

        var maxValue = 0;
        var maxValueschl = 0;
        var _row = null;
        var subjctpriorty = 1, schllvlpriorty = 1;
       function TutorCourseReset() {
       if ($("#updateButton").text() == "Update") {
           $("#updateButton").text("Add");
           $('#ddlSubject').val('');
           $('#ddlSchoollevel').val('');
           $('#ddlSelectedCourse').empty();
           $('#ddlCourse').empty();

           var tutcoursUrl = '@Url.Action("GetCourseTutbucket", "Common", new { Area = "" })';
           $.ajax({
               type: "GET",
               url: tutcoursUrl,
               contentType: "application/json; charset=utf-8",
               dataType: "json",
               success: function (data) {
                   debugger;
                   if (data != undefined && data.length > 0) {
                       $.each(data, function (i, Course) {
                           debugger;
                           $('#ddlCourse').append('<option value=' + Course.Value + '>' + Course.Text + '</option>');
                       });

                   }
               },
               error: function (data) {
                   alert("fail");
               }

           });
       }
       else {
           $("#updateButton").text("Add");
           $('#ddlSubject').val('');
           $('#ddlSchoollevel').val('');
           $('#ddlSelectedCourse').empty();
           $('#ddlCourse').empty();

           var tutcoursUrl = '@Url.Action("GetCourseTutbucket", "Common", new { Area = "" })';
           $.ajax({
               type: "GET",
               url: tutcoursUrl,
               contentType: "application/json; charset=utf-8",
               dataType: "json",
               success: function (data) {
                   debugger;
                   if (data != undefined && data.length > 0) {
                       $.each(data, function (i, Course) {
                           debugger;
                           $('#ddlCourse').append('<option value=' + Course.Value + '>' + Course.Text + '</option>');
                       });

                   }
               },
               error: function (data) {
                   alert("fail");
               }

           });
       }
       }
    function resetfields() {
        debugger;

        $('#ddlSubject').val('');
        $('#ddlSchoollevel').val('');
        $('#ddlSelectedCourse').empty();

         var tutcoursUrl = '@Url.Action("GetCourseTutbucket", "Common", new { Area = "" })';
            $.ajax({
                type: "GET",
                url: tutcoursUrl,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    debugger;
                    if (data != undefined && data.length > 0) {
                        $.each(data, function (i, Course) {

                            $('#ddlCourse').append('<option value=' + Course.Value + '>' + Course.Text + '</option>');
                        });

                    }
                },
                error: function (data) {
                    alert("fail");
                }

            });

            }
       
    function TutorCourseDelete(ctl) {
        debugger;
        $(ctl).closest("tr").remove();
       
    }
    function TutorCourseEdit(ctl) {
        debugger;

        var row = $(ctl).closest("tr");

        _activeId = row.find('.btnedit').data("id");
        subjctpriorty = row.find('[name=subjctpriorty]').html();
        schllvlpriorty = row.find('[name=schllvlpriorty]').html();
        var subject = row.find("[name=sub]").text();
        var subjectId = row.find("[name=subId]").text();
        var schoollevel = row.find("[name=sclevl]").text();
        var schoollevelId = row.find("[name=sclevlId]").text();
        var selectedcourses = row.find("[name=selectdcours]").text();
        var selectedcoursesId = row.find("[name=selectdcoursId]").text();

        var splitcoursereplce = selectedcoursesId.replace(/,\s*$/, "");
        var splitcourseIdsplt = splitcoursereplce.split(",");
        var splitcoursesrplc = selectedcourses.replace(/,\s*$/, "");
        var splitcoursessplt = splitcoursesrplc.split(",");


        $("#ddlSubject").val(subjectId).focus();
        $("#ddlSchoollevel").val(schoollevelId);
        $('#ddlSelectedCourse option').remove();

        if (subjectId != null && subjectId != '') {

            var selectedsubjectID = subjectId;

            var courseUrl = '@Url.Action("GetCourseOnSubject", "Login", new { Area = "" })';
            var CourseValues = populateValues(selectedsubjectID, courseUrl);
            $('#ddlCourse').html('');
            if (CourseValues != undefined && CourseValues.length > 0) {
                $.each(CourseValues, function (i, Course) {

                    $('#ddlCourse').append('<option value=' + Course.Value + '>' + Course.Text + '</option>');
                });

            }


        }

        splitcourseIdsplt.forEach((num1, index) => {
            const num2 = splitcoursessplt[index];

            $('#ddlSelectedCourse').append('<option value=' + num1 + '>' + num2 + '</option>');
        });

        var courser = document.getElementById("ddlCourse");
        var selectedcourser = document.getElementById("ddlSelectedCourse");
        for (var i = 0; i < courser.length; i++) {
            debugger;
            var cours = courser[i];
            debugger;
            for (var j = 0; j < selectedcourser.length; j++) {
                var selectcours = selectedcourser[j];
                debugger;
                if (cours.value == selectcours.value) {
                    courser.remove(i);
                    i--;
                }

            }

        }
        // Change Update Button Text
        $("#updateButton").text("Update");
    }

        function TutorCourseUpdate() {
            debugger;
            if ($("#updateButton").text() == "Update") {
                TutorCourseUpdateInTable(_activeId);
            }
            else if ($('#ddlSubject').val() == null || $('#ddlSubject').val() == '') {

                alert("please select subject")
                return false;
            }

            else if ($('#ddlSchoollevel').val() == null || $('#ddlSchoollevel').val() == '') {
                alert("please select school level")
                return false;
            }
            else if ($('#ddlSelectedCourse option').val() == null || $('#ddlSelectedCourse option').val() == '') {
                alert("Please select atleast one Course")
                return false;

            }

            else {
                TutorCourseAddToTable();
            }


            // Clear form fields
            resetfields();

        }

        function TutorCourseUpdateInTable(id) {
            debugger;

        // Find TutorCourse in <table>
           // var row = $("#tbl_TutorcoursList button[data-id='" + id + "']")
            //    .parents("tr")[0];
            var row = $("#tbl_TutorcoursList").find('.btnedit[data-id="' + id + '"]').closest('tr');

        // Add changed Tutorcourse to table
        $(row).after(TutorCourseTableRow(id));
        // Remove original TutorCourse
        $(row).remove();
        $("#updateButton").text("Add");
        resetfields();

    }
           function TutorCourseAddToTable() {
               debugger;

        let tab = $('#tblBody_TutorcoursList');
        // Append TutorCourse to table
        tab.append(TutorCourseTableRow(_nextId));

        // Increment next ID to use
        _nextId += 1;

    }

        function TutorCourseTableRow(id) {
            debugger;
            var datas = [];
        var Subject = $('#ddlSubject option:selected').text().trim();
        var SubjectId = $('#ddlSubject').val().trim();
        var SchoolLevel = $('#ddlSchoollevel option:selected').text().trim();
        var SchoolLevelId = $('#ddlSchoollevel').val().trim();
     

            $('#tbl_TutorcoursList tbody tr').each(function () {
                debugger;
                var $tblrow = $(this);
                var subject = $tblrow.find("[name=sub]").text();
                var schoolLevel = $tblrow.find("[name=sclevl]").text();
                var subPriorty = $tblrow.find("[name=subjctpriorty]").text();
                var schlPriorty = $tblrow.find("[name=schllvlpriorty]").text();

                var obj = {};
                obj.Subject = subject;
                obj.SchoolLevel = schoolLevel;
                obj.subjectPriorty = subPriorty;
                obj.SchoolPriorty = schlPriorty;
                datas.push(obj);
            });

            if (datas.length > 0) {
                for (var i = 0; i < datas.length; i++) {
                    debugger;
                    if (datas[i].Subject == Subject) {
                        subjctpriorty = datas[i].subjectPriorty;
                        break;
                    }
                    else {
                        var sub = [];
                        datas.filter(function (item) {
                            debugger;
                            if (sub.indexOf(item.Subject) == -1) {
                                sub.push(item.Subject);
                            }
                        });
                        subjctpriorty = sub.length + 1;
                    }
                }

                for (var i = 0; i < datas.length; i++) {
                    debugger;
                    var result = datas.filter(function (el) {
                        debugger;
                        return el.Subject == Subject;
                    });
                    schllvlpriorty = result.length + 1;
                }
            }



        var selectedCourses = '';
        var selectedCourseIDs = '';

        $.each($('#ddlSelectedCourse option'), function (key, value) {
            selectedCourseIDs += $(this).val() + ',';
        });
        $.each($('#ddlSelectedCourse option'), function (key, value) {
            selectedCourses += $(this).text() + ',';
        });
       selectedCourseIDs = selectedCourseIDs.replace(/,\s*$/, "");

       selectedCourses = selectedCourses.replace(/,\s*$/, "");

        var ret = '<tr><td name="sub">' + Subject + '</td><td hidden name="subId">' + SubjectId + '</td><td name="sclevl">' + SchoolLevel + '</td><td hidden name="sclevlId">' + SchoolLevelId + '</td><td name="selectdcours">' + selectedCourses + '</td><td hidden name="selectdcoursId">' + selectedCourseIDs + '</td><td name="subjctpriorty">' + subjctpriorty + '</td><td name="schllvlpriorty">' + schllvlpriorty + '</td><td><i title="Click on this button to edit the details" class="fa fa-pencil btnedit fev-cursor" aria-hidden="true" onclick= "TutorCourseEdit(this)"; data-id=' + id + '></i><i title="Click on this button to delete the details" class="fa fa-trash btndelete color-red fev-cursor ml10" aria-hidden="true" onclick= "TutorCourseDelete(this)";" data-id=' + id + '></i></td></td></tr>'

        return ret;
    }

 

<div class="row">
        <div class="col-sm-12">
            <table id="tbl_TutorcoursList" style="table-layout:fixed;word-wrap:break-word" class="table table-hover table-bordered table-striped table-responsive">
                <thead>
                    <tr>

                        <th>Subject</th>
                        <th hidden>SubjectId</th>
                        <th>School level</th>
                        <th hidden>School levelId</th>
                        <th>Course</th>
                        <th hidden>CourseId</th>
                        <th>Subject Priority</th>
                        <th>School level Priority</th>
                        <th>Action</th>
                        @*<th>Edit </th>
                            <th>Delete</th>*@



                    </tr>
                </thead>
                <tbody id="tblBody_TutorcoursList"></tbody>
            </table>
        </div>
    </div>

 

<div class="row ">
                    <div class="col-sm-12 text-right">
                        <button type="button"
                                id="updateButton"
                                class="btn btn-success"
                                onclick="TutorCourseUpdate();">
                            Add
                        </button>


                        <button type="button"
                                id="ResetButton"
                                class="btn btn-danger" style="color: #ffffff; background-color: #f4ad49; border-color: #f4ad49;"
                                onclick="TutorCourseReset();">
                            Reset
                        </button>
                    </div>
                </div>

Hi,I need to implement on delete functionality

The scenarios working right now are

If i click on add button the below scenarios works

a)subject changes-subject priorty will get increment and school level priorty remains same if sujbject changes school level remains same b)subject remains same and school level priorty keep on incremenet if subject is same and school level changes

This above scenario is working same thing want to implement on delete functionality

I provided my UI in below link

https://ibb.co/XStL6yG

In this UI if i delete second 2nd row the third row should become subject priorty remains same and school level priority(only subject priorty and schoollevel priorty should other should remains same of 3rd row) should change to 2 and and 2nd row will get delete

Remember it should not work like for all rest other it should normally delete

Only this logic should work in those positions which we are trying to delete in between due to this sequence will get shuffle

You alredy helped me in acheiving in add functionality in my previous query

Could you please help me in this?

You are viewing reply posted by: Andrea 6 days ago.
Posted 6 days ago
Hi @zeeshanpas,
Please try the following

Update counter after delete row from HTML Table using JavaScript in ASP.Net MVC

It might help you.

Cheers Andrea.