locked
Get ID Of Each Row Where Checkbox Value Changed RRS feed

  • Question

  • User974100899 posted

    I have a table that has 3 columns, id, employeename, active (active is a checkbox).

    I am pressing a save button and I want to save the udpates to the database.  Which means I need to be able to determine which rows have the checkbox property changed - meaning go from checked to unchecked or vice versa unchecked to checked.

    Using JavaScript how I capture the ID of those rows so I can update those rows in my database?

    Wednesday, October 23, 2019 8:38 PM

Answers

  • User665608656 posted

    Hi LiarLiarPantsOnFire ,

    According to your description and code, I suggest that you use the following methods to create checkboxes when you add checkboxes to the active column, and add a click event when you create it, so that you can enter the corresponding click event when you click the checkbox.

    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet" /> 
        <script src="https://code.jquery.com/jquery-3.3.1.js "> </script>
        <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"> </script> 
        <script> 
            var arraCheck = [];
            $(document).ready(function () {
    
                $("#tblDetail").DataTable({
                    "ajax": {
                        type: "POST",
                        url: "WebForm_1024_2160903.aspx/GetQueryInfo",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        dataSrc: function (json) {
                            var msg = $.parseJSON(json.d);
                            return msg.data;
                        },
                    },
                    "columns": [
                        { "data": "id" },
                        { "data": "employeeName" },
                        {
                            data: "active",
                            render: function (data, type, row) {
                                if (data) {
                                    return '<input type="checkbox" class="editor-active"  checked onclick="CheckMethod(this)">';
                                } else {
                                    return '<input type="checkbox" class="editor-active"  onclick="CheckMethod(this)">';
                                }
                                return data;
                            },
                        }
                    ]
                });
    
    
                $("#Button1").click(function () {
                    event.preventDefault();
                    $.ajax({
                        type: 'POST',
                        url: 'WebForm_1024_2160903.aspx/SaveChangedCheckBox',
                        contentType: 'application/json; charset=utf-8',
                        data: JSON.stringify({ arraCheck: arraCheck }),
                        dataType: 'json',
                        success: function (r) {
                            alert("save successfully!");
                        }
                    });
    
                })
    
    
            });
    
            function CheckMethod(chebox) {
                var id = $(chebox).parents("tr").find("td")[0].innerHTML;
                var emplyeeName = $(chebox).parents("tr").find("td")[1].innerHTML;
                var isCheck = $(chebox).prop("checked");
                var obj = { "id": id, "emplyeeName": emplyeeName, "active": isCheck };
                var retVal = containsObject(id, arraCheck);
                //ensure only add the changed data
                if (/^\d+$/.test(retVal)) {
                    arraCheck.splice(retVal, 1);
                } else {
                    arraCheck.push(obj);
                }
    
            }
            function containsObject(obj, list) {
                var i;
                for (i = 0; i < list.length; i++) {
                    if (list[i].id === obj) {
                        return i;
                    }
                }
                return "false";
            }
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <asp:Button ID="Button1" runat="server" Text="Save" />
            <div class="div1">
                <div class="div3">
                    <table id="tblDetail" class="dispaly" style="width: 95%">
                        <thead class="thead-light">
                            <tr>
                                <th>ID
                                </th>
                                <th>Employee Name
                                </th>
                                <th>Active
                                </th>
                            </tr>
                        </thead>
                    </table>
                </div>
            </div>
        </form>
    </body>
    </html>
    
            [WebMethod]
            public static string GetQueryInfo()
            {
                List<EmplyAct> emplyActs = new List<EmplyAct>() {
                    new EmplyAct{ id=2059,employeeName="Test1",active=true},
                    new EmplyAct{ id=2005,employeeName="Test2",active=true},
                    new EmplyAct{ id=3386,employeeName="Test3",active=false},
                     new EmplyAct{ id=2015,employeeName="Test5",active=true},
                      new EmplyAct{ id=1084,employeeName="Test6",active=false},
                };
                var json = JsonConvert.SerializeObject(emplyActs);
                return "{\"data\":" + json + "}";
            }
    
            [WebMethod]
            public static void SaveChangedCheckBox(List<EmplyAct> arraCheck)
            {
              //loop the list to change your data
            }
       
    
        public class EmplyAct
        {
            public int id { get; set; }
            public string employeeName { get; set; }
            public bool active { get; set; }
        }

    Here is the result:

    Best Regards,

    YongQing.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, October 24, 2019 9:37 AM

All replies

  • User475983607 posted

    LiarLiarPantsOnFire

    Using JavaScript how I capture the ID of those rows so I can update those rows in my database?

    Share your code if you want community debugging support.  Otherwise you're forcing the community to guess how your HTML is formatted which causes several unnecessary posts.

    Wednesday, October 23, 2019 8:52 PM
  • User974100899 posted

    Here is my JSON that is populating my table

    {
      "data": [
        {
          "id": 2059,
          "employeeName": "Test1",
          "active": true
        },
        {
          "id": 2005,
          "employeeName": "Test2",
          "active": true
        },
        {
          "id": 3386,
          "employeeName": "Test3",
          "active": true
        },
        {
          "id": 2015,
          "employeeName": "Test5",
          "active": true
        },
        {
          "id": 1084,
          "employeeName": "Test6",
          "active": true
        }
      ]
    }

    and this is my javascript:

    $('#btnARS').click(function () {
    tblARS = $('#tblARS').DataTable({
    dom: 'Bfrtip',
    buttons: ['copy', 'csv', 'excel', 'pdf', 'print'],
    ajax: {
    type: 'Get',
    dataType: 'json',
    url: 'https://localhost:44328/api/adrAR',
    data: {
    json: JSON.stringify(data)
    }
    },
    columns: [
    {
    data: "id"
    },
    {
    data: "employeeName"
    },
    {
    data: "active", render: function (data, type, row, meta) {
    var checkbox = $('<input/>', {
    type: 'checkbox'
    });
    if (row[2] = 'true') {
    checkbox.attr('checked', 'checked');
    checkbox.addClass('checkbox_checked');
    } else {
    checkbox.removeAttr('checked');
    checkbox.addClass('checkbox_unchecked');
    }
    return checkbox.prop('outerHTML');
    }
    }
    ]
    })
    });

    Wednesday, October 23, 2019 8:55 PM
  • User475983607 posted

    That does not really clarify a thing but you can get all the checked checkboxes with a the following jQuery selector.

    https://api.jquery.com/checked-selector/

    $( "input:checked" )

    From there you can loop over the checkboxes and find the closest parent row.

    $( "input:checked" ).each(function(index, value){
       var row = $(value).closest('tr');
    });

    Use find('selector') to get to the other elements values with in the row.  You can use the same technique for finding unchecked checkboxes.  I'm not sure how you want to manage state change.  If you'll compare the UI state to the DB or something in code or one check at a time.

    For example, just loop over every row and build an json object and send the entire object to the server. This represents the current state of the UI.  Use this to update the DB.

    Remember to use the browser's dev tools to debug your code.

    Wednesday, October 23, 2019 9:41 PM
  • User974100899 posted

    The above code was what I have in place...nothing that checks for checked or unchecked events.  

    I'm wanting to get the changed checkbox events as the database will need to be updated to reflect any employee that is flagged as Active that was previously inactive or any employee that was previously Active that is now in-active or any new employee that is added and by default set to active.

    Those are the events I'm trying to capture to pass back to the database.

    Wednesday, October 23, 2019 11:58 PM
  • User665608656 posted

    Hi LiarLiarPantsOnFire ,

    According to your description and code, I suggest that you use the following methods to create checkboxes when you add checkboxes to the active column, and add a click event when you create it, so that you can enter the corresponding click event when you click the checkbox.

    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet" /> 
        <script src="https://code.jquery.com/jquery-3.3.1.js "> </script>
        <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"> </script> 
        <script> 
            var arraCheck = [];
            $(document).ready(function () {
    
                $("#tblDetail").DataTable({
                    "ajax": {
                        type: "POST",
                        url: "WebForm_1024_2160903.aspx/GetQueryInfo",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        dataSrc: function (json) {
                            var msg = $.parseJSON(json.d);
                            return msg.data;
                        },
                    },
                    "columns": [
                        { "data": "id" },
                        { "data": "employeeName" },
                        {
                            data: "active",
                            render: function (data, type, row) {
                                if (data) {
                                    return '<input type="checkbox" class="editor-active"  checked onclick="CheckMethod(this)">';
                                } else {
                                    return '<input type="checkbox" class="editor-active"  onclick="CheckMethod(this)">';
                                }
                                return data;
                            },
                        }
                    ]
                });
    
    
                $("#Button1").click(function () {
                    event.preventDefault();
                    $.ajax({
                        type: 'POST',
                        url: 'WebForm_1024_2160903.aspx/SaveChangedCheckBox',
                        contentType: 'application/json; charset=utf-8',
                        data: JSON.stringify({ arraCheck: arraCheck }),
                        dataType: 'json',
                        success: function (r) {
                            alert("save successfully!");
                        }
                    });
    
                })
    
    
            });
    
            function CheckMethod(chebox) {
                var id = $(chebox).parents("tr").find("td")[0].innerHTML;
                var emplyeeName = $(chebox).parents("tr").find("td")[1].innerHTML;
                var isCheck = $(chebox).prop("checked");
                var obj = { "id": id, "emplyeeName": emplyeeName, "active": isCheck };
                var retVal = containsObject(id, arraCheck);
                //ensure only add the changed data
                if (/^\d+$/.test(retVal)) {
                    arraCheck.splice(retVal, 1);
                } else {
                    arraCheck.push(obj);
                }
    
            }
            function containsObject(obj, list) {
                var i;
                for (i = 0; i < list.length; i++) {
                    if (list[i].id === obj) {
                        return i;
                    }
                }
                return "false";
            }
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <asp:Button ID="Button1" runat="server" Text="Save" />
            <div class="div1">
                <div class="div3">
                    <table id="tblDetail" class="dispaly" style="width: 95%">
                        <thead class="thead-light">
                            <tr>
                                <th>ID
                                </th>
                                <th>Employee Name
                                </th>
                                <th>Active
                                </th>
                            </tr>
                        </thead>
                    </table>
                </div>
            </div>
        </form>
    </body>
    </html>
    
            [WebMethod]
            public static string GetQueryInfo()
            {
                List<EmplyAct> emplyActs = new List<EmplyAct>() {
                    new EmplyAct{ id=2059,employeeName="Test1",active=true},
                    new EmplyAct{ id=2005,employeeName="Test2",active=true},
                    new EmplyAct{ id=3386,employeeName="Test3",active=false},
                     new EmplyAct{ id=2015,employeeName="Test5",active=true},
                      new EmplyAct{ id=1084,employeeName="Test6",active=false},
                };
                var json = JsonConvert.SerializeObject(emplyActs);
                return "{\"data\":" + json + "}";
            }
    
            [WebMethod]
            public static void SaveChangedCheckBox(List<EmplyAct> arraCheck)
            {
              //loop the list to change your data
            }
       
    
        public class EmplyAct
        {
            public int id { get; set; }
            public string employeeName { get; set; }
            public bool active { get; set; }
        }

    Here is the result:

    Best Regards,

    YongQing.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, October 24, 2019 9:37 AM
  • User974100899 posted


    @Yongqing Yu ->

    how does the SaveChangedCheckBox C# method get set-up?

    In the button click event on this line of code

    data: JSON.stringify({ arraCheck: arraCheck }),

    I get this error in the dev console:

    UncaughtReferenceError: arraCheck is not defined.

    Thursday, November 7, 2019 3:23 PM