We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy.
Unfortunately, activation email could not send to your email. Please try again.
Syncfusion Feedback

Adding check box to grid but not get initialized and when switch in second page that check box get unchecked

Thread ID:

Created:

Updated:

Platform:

Replies:

120072 Aug 28,2015 07:09 AM UTC Sep 8,2015 04:28 AM UTC JavaScript 7
loading
Tags: ejGrid
Gomtesh
Asked On August 28, 2015 07:09 AM UTC

Hi,
   I have used check-box column in syncfusion grid
  1.
      but it is not get initialized when grid is loaded but when i click on selectall checkbox its get initialized i have to get initialized that row checkboxes when grid is get loaded. because i have to get record of selected row and event of that checkbox is checked or unchecked
  2.
     Also when i check one row and switch to next page and again come on previous page checked row are are get unchecked  i have make that whatever checkboxes i have checked on previous page that should be remains state (i.e checked or unchecked state).


The above functionality i have done in AngularJS

Here is the code:::

HTML code is::
 <!--Code corresponding to columnTemplate-->
    <script type="text/x-jsrender" id="checkboxTemplate">
        <input type="checkbox" class="rowCheckbox" />
        </script>
 
    <!--Code corresponding to headerTemplate-->
    <script type="text/x-jsrender" id="headerTemplate">
        <input type="checkbox" id="headchk" />
    </script>

<div ng-controller="ContactListController">
    <div id="Grid" ng-init="chkinit()" ej-grid e-datasource="data" e-columns="columns" e-recordclick="recordClick" e-allowselection="true" e-selectiontype="multiple" e-actioncomplete= "complete"     e-allowsorting="allowsorting" e-sortsettings="sortsettings" e-complete="complete" e-create="create" e-allowpaging="allowpaging" e-pagesettings="pagesettings"></div>
 </div>



controller code:::


App.controller('ContactListController', function ($scope) {

 var gridObj;
    var newColumns = [                    
                          { headerTemplateID: "#headerTemplate", template: true, templateID: "#checkboxTemplate", textAlign: ej.TextAlign.Center, width: 20 },
                          { field: "Name", headerText: "Name", width: 75, textAlign: ej.TextAlign.Right },
                          { field: "MobileNumber", headerText: "Number", width: 75, textAlign: ej.TextAlign.Right },
                          { field: "Email", headerText: "Email", width: 75, textAlign: ej.TextAlign.Right },
                          { field: "BirthDate", headerText: "Birthdate", format: "{0:dd-MMM-yyyy}", width: 75, textAlign: ej.TextAlign.Right },
                          { field: "AnniversaryDate", headerText: "Anniversary ", format: "{0:dd-MMM-yyyy}", width: 75, textAlign: ej.TextAlign.Right },
                          { field: "Gender", headerText: "Gender ", width: 75, textAlign: ej.TextAlign.Right },
                          {
                              headerText: "",
                              commands: [
                                         {
                                             type: "",
                                             buttonOptions: {
                                                 htmlAttributes: { id: "CustomButton", class: "btn-white btn-sm editClick", style: " width: 60px;" },
                                                 text: "Edit",
                                                 click: "onClick"
                                             }
                                         }
                              ],

                              isUnbound: true,
                              textAlign: ej.TextAlign.Center,
                              width: 70
                          }
    ];

    $scope.columns = newColumns;

    $scope.tools = { showToolbar: false, toolbarItems: [ej.Grid.ToolBarItems.Add, ej.Grid.ToolBarItems.Edit, ej.Grid.ToolBarItems.Delete, ej.Grid.ToolBarItems.ExcelExport, ej.Grid.ToolBarItems.WordExport, ej.Grid.ToolBarItems.PdfExport, ej.Grid.ToolBarItems.PrintGrid] };

    $scope.data = ej.DataManager({ url: "http://localhost:63138//api/Contact/GetContactsbyClientId?clientId=1", adaptor: "WebApiAdaptor", offline: true });

    $scope.allowpaging = { allowPaging: true };

    $scope.pagesettings = { pageSize: 11 };

  $scope.editClick = function (args) {
        var grid = $("#Grid").ejGrid("instance");
        var index = this.element.closest("tr").index();
        var record = grid.getCurrentViewData()[index];
        alert(JSON.stringify(record))
    }

 $scope.recordClick = function (args) {
        $("#Grid .editClick").ejButton({ "click": $scope.editClick });

        if (this.multiSelectCtrlRequest == false) {
            for (var i = 0; i < $("#Grid .rowCheckbox").length; i++)
           //     $($("#Grid .rowCheckbox")[i]).ejCheckBox({ "checked": false })  //To clear checkbox when we select row by recordclick rather than checkbox
            this.clearSelection();
           // $("#headchk").ejCheckBox({ "checked": false });
        }
    }

 var gridObj;

    function headCheckChange(e) {
        $("#Grid .rowCheckbox").ejCheckBox({ "change": checkChange });
        gridObj = $("#Grid").data("ejGrid");
        if ($("#headchk").is(':checked')) {
            $(".rowCheckbox").ejCheckBox({ "checked": true });
            gridObj.multiSelectCtrlRequest = true;
            gridObj.selectRows(0, gridObj.model.pageSettings.pageSize);  // To Select all rows in Grid Content
        }
        else {
            $(".rowCheckbox").ejCheckBox({ "checked": false });
            gridObj.clearSelection(); // To remove selection for all rows
        }
    }

    function checkChange(e) {
        gridObj = $("#Grid").data("ejGrid");
        var rowCheck = $(".rowCheckbox:checked");
        if (rowCheck.length == gridObj.model.pageSettings.pageSize)//check if all checkboxes in the current page are checked
            $("#headchk").ejCheckBox({ "checked": true });
        else
            $("#headchk").ejCheckBox({ "checked": false });

        if (($("#headchk").is(':checked')) && this.model.checked != true) {
            for (i = 0; i < rowCheck.length; i++) {
                gridObj.multiSelectCtrlRequest = true;
                gridObj.selectRows($(rowCheck[i]).parents("tr").index());// To prevent unselection of other rows when a checkbox is unchecked after selectAll rows
            }
            //gridObj.clearSelection($(this).parents("tr").index()); // To remove selection of current row when the checkbox is unchecked after selectAll rows
        }
        if (this.model.checked == false) {
            $("#headchk").ejCheckBox({ "checked": false });
            //$("#Grid .rowCheckbox").ejCheckBox({ "checked": false });
        }
        gridObj.multiSelectCtrlRequest = true;//For MultiSelection using Checkbox
    }

    $scope.create = function (args) {
        $("#Grid .rowCheckbox").ejCheckBox({ "change": checkChange });
        $("#headchk").ejCheckBox({ "change": headCheckChange });
    }
    $scope.complete = function (args) {
        console.log(args.mode.currentViewData);
        $("#Grid .rowCheckbox").ejCheckBox({ "change": checkChange });
        $("#headchk").ejCheckBox({ "change": headCheckChange, checked: false });
    }

});

Madhu Sudhanan P [Syncfusion]
Replied On August 31, 2015 09:41 AM UTC

Hi Gomtesh,

Thanks for contacting Syncfusion support.

Query #1: “it is not get initialized when grid is loaded but when i click on selectall checkbox its get initialized”

The cause of the issue is due to that the checkboxes are rendered in the create event of the grid. When comes with remote data binding in grid, the create event will be triggered before the grid content gets ready and hence the checkboxes are not get initialized as ejCheckBox.

 To resolve this, we suggest you to use the dataBound event to render any sub controls on initial rendering and templateRefresh for rendering them after any other subsequent grid actions as follows.


<div id="Grid" ng-init="chkinit()" ej-grid e-datasource="data" e-columns="columns"

             e-recordclick="recordClick" e-allowselection="true" e-selectiontype="multiple"

             e-actioncomplete="actioncomplete" e-allowsorting="allowsorting"

             e-templaterefresh="refreshTemplate"

             e-databound="dataBound" e-actionbegin="actionbegin"

              e-allowpaging="allowpaging" e-pagesettings="pagesettings"></div>
    </div>

             $scope.dataBound = function (args) {

                $("#Grid .rowCheckbox").ejCheckBox({ "change": checkChange });

                $("#headchk").ejCheckBox({ "change": headCheckChange });

                this.model.indexes = {};

            }

            $scope.refreshTemplate = function (args) {

                $("#Grid .rowCheckbox").ejCheckBox({ "change": checkChange });

                $("#headchk").ejCheckBox({ "change": headCheckChange, checked: false });
            }


Query #2: “when i check one row and switch to next page and again come on previous page checked row are get unchecked”

Based on your requirement we have created a simple sample with your code example in which the selection is maintained on paging and the same can be referred from the below link.

http://jsplayground.syncfusion.com/j15dqpl4

In the above sample, we have added an additional property to the grid` model to maintain the selected row index throughout the paging. Please refer the following code example.


            $scope.dataBound = function (args) {

                $("#Grid .rowCheckbox").ejCheckBox({ "change": checkChange });

                $("#headchk").ejCheckBox({ "change": headCheckChange });

                this.model.indexes = {}; /* Additional property*/

            }           

            $scope.actionbegin = function (args) {

                //Stores the selected index on paging starts.

                if (args.requestType == "paging") {

                    if (this.selectedRowsIndexes.length > 0)

                    this.model.indexes[args.previousPage] = this.selectedRowsIndexes;

                }

            }


            $scope.actioncomplete = function (args) {

                //Retriev and select the rows on paging ends

                if (args.requestType == "paging") {                   

                    var indx = this.model.indexes[args.currentPage];

                    for (var i = 0; i < (indx || []).length; i++) {

                        $("#Grid .rowCheckbox").eq(indx[i]).ejCheckBox("model.checked", true)

                        this.selectRows(indx[i]);

                    }                   

                }
            }


Please let us know if you have any query.

Regards,
Madhu Sudhanan. P

Gomtesh
Replied On August 31, 2015 10:29 AM UTC

Hi Madhu,
Thanks for reply.
You given nice demo on ESSENTIAL JSPLAYGROUND
As you given solution on following link:
http://jsplayground.syncfusion.com/j15dqpl4

But it has some issue

1. As you check some records  and when switch to next page and come back to previous page sometimes its get unchecked and sometimes its given proper result i.e.  inconsistent result it shown

2. And second issue is that when i run your demo and click on edit button the alert message is not getting but when i click on second time it gives proper alert.

So please help.


Madhu Sudhanan P [Syncfusion]
Replied On September 1, 2015 09:25 AM UTC

Hi Gomtesh,

Query #1: “As you check some records  and when switch to next page and come back to previous page sometimes its get unchecked and sometimes its given proper result i.e.  inconsistent result it shown”

We tried to reproduce the issue with the provided replication procedure and we are unable to reproduce this issue in the given sample and its working fine for us. And could you please provide more information such as video, screenshot or clear replication procedure to reproduce the issue.

Query #2: “And second issue is that when i run your demo and click on edit button the alert message is not getting but when i click on second time it gives proper alert”

The cause of this issue is due to that the click handler is specified as string value for the command button as follows.


 var newColumns = [

                  . . .  . .

                                  {

                                      headerText: "",

                                      commands: [

                                                 {

                                                     type: "",

                                                     buttonOptions: {

                                                         htmlAttributes: { id: "CustomButton", class: "btn-white btn-sm editClick", style: " width: 60px;" },

                                                         text: "Edit",

                                                         click: "editClick"

                                                     }

                                                 }

                                      ],


                                      isUnbound: true,

                                      textAlign: ej.TextAlign.Center,

                                      width: 70

                                  }
            ];


When the handler name is provided as in the above code, to invoke the handler on click, the handler will be searched in the context of window instead of scope and hence the button click was not fired first time. And we have also noticed that the click event for the buttons were registered again in the recordClick event of the grid. Due to the following line the alert message was showed at the second click.


<div id="Grid" ng-init="chkinit()" ej-grid e-datasource="data" e-columns="columns"

             e-recordclick="recordClick" . . . .>
    </div>

$scope.recordClick = function (args) {

                $("#Grid .editClick").ejButton({ "click": $scope.editClick });


                . . . .
            }


To resolve this issue, we suggest you to provide the click handler directly from the scope instead of providing string name. Please refer the below code example.


            $scope.editClick = function (args) {

                var grid = $("#Grid").ejGrid("instance");

                var index = this.element.closest("tr").index();

                var record = grid.getCurrentViewData()[index];

                alert(JSON.stringify(record))

            }


            var newColumns = [

                          . . .  .

                                  {

                                      headerText: "",

                                      commands: [

                                                 {

                                                     type: "",

                                                     buttonOptions: {

                                                         htmlAttributes: { id: "CustomButton", class: "btn-white btn-sm editClick", style: " width: 60px;" },

                                                         text: "Edit",

                                                         click: $scope.editClick

                                                     }

                                                 }

                                      ],


                                      isUnbound: true,

                                      textAlign: ej.TextAlign.Center,

                                      width: 70

                                  }

            ];


            . . . .

            $scope.recordClick = function (args) {

               

                //No need for this line

                 $("#Grid .editClick").ejButton({ "click": $scope.editClick });


                . . .  .
            }


We have also modified the previously provided sample and the same can be referred from the following link.

http://jsplayground.syncfusion.com/1la3phjd

Please let us know if you have any query.

Regards,
Madhu Sudhanan. P

Gomtesh
Replied On September 2, 2015 04:30 AM UTC

Hi Madhu,
Thanks for giving solution its working.

I have one more issue is this possible when i check selectAll checkbox on any one of page the all records get checked and if i uncheck selectall checkbox on any one of page all checkboxes from every page get unselected

but currently only single page records get selected when i check selectall checkbox.

Thanks once again,

Madhu Sudhanan P [Syncfusion]
Replied On September 4, 2015 11:35 AM UTC

Hi Gomtesh,

Sorry for the delay in getting back to you.

The requirement “Select/unselect all records in the grid using header checkbox” can be achieved with the following changes in the previously provided sample. Please refer the below code example.


            function headCheckChange(e) {

                $("#Grid .rowCheckbox").ejCheckBox({ "change": checkChange });

                gridObj = $("#Grid").data("ejGrid");

                var pager = gridObj.model.pageSettings;

                if ($("#headchk").is(':checked')) {

                    $(".rowCheckbox").ejCheckBox({ "checked": true });

                    gridObj.multiSelectCtrlRequest = true;

                    gridObj.selectRows(0, pager.pageSize);  // To Select all rows in Grid Content


                    //To maintain the selected indexes for all pages

                    for (var i = 1, j; i <= pager.totalPages; i++) {

                        var ind = gridObj.model.indexes[i] = [];

                        j = i == pager.totalPages ? pager.totalRecordsCount % pager.pageSize : pager.pageSize;

                        while (--j != -1) {

                            ind.push(j);                           

                        }

                    }

                }

                else {

                    $(".rowCheckbox").ejCheckBox({ "checked": false });

                    gridObj.model.indexes = {};

                    gridObj.clearSelection(); // To remove selection for all rows

                }

            }


            function checkChange(e) {

                gridObj = $("#Grid").data("ejGrid");

                var rowCheck = $(".rowCheckbox:checked"), cp = gridObj.model.pageSettings.currentPage;

                gridObj.model.indexes[cp] = gridObj.model.indexes[cp] || [];

                var ind = gridObj.model.indexes[cp], row = this.element.closest("tr").index();

                if (this.model.checked)                

                    ind.push(row);               

                else

                    ind.splice(ind.indexOf(row), 1);


                var total = gridObj.model.pageSettings.totalRecordsCount, chks = 0;

                for (var p in gridObj.model.indexes) {

                    chks += gridObj.model.indexes[p].length

                }             

                if (total == chks) /*check whether all checkboxes are clicked*/

                    $("#headchk").ejCheckBox({ "checked": true });

                else

                    $("#headchk").ejCheckBox({ "checked": false });


                if (($("#headchk").is(':checked')) && this.model.checked != true) {

                    for (i = 0; i < rowCheck.length; i++) {

                        gridObj.multiSelectCtrlRequest = true;

                        gridObj.selectRows($(rowCheck[i]).parents("tr").index());// To prevent unselection of other rows when a checkbox is unchecked after selectAll rows

                    }                  

                }

                if (this.model.checked == false) {

                    $("#headchk").ejCheckBox({ "checked": false });                  

                }

                gridObj.multiSelectCtrlRequest = true;//For MultiSelection using Checkbox
            }

           $scope.actioncomplete = function (args) {

                //Retriev and select the rows on paging ends

                if (args.requestType == "paging") {                   

                    var hc = $("#headchk").ejCheckBox("model.checked"); //Checked for header checkbox

                    var indx = this.model.indexes[args.currentPage];

                    for (var i = 0; i < (hc ? this.model.currentViewData : (indx || [])).length; i++) {

                        $("#Grid .rowCheckbox").eq(hc ? i : indx[i]).ejCheckBox("model.checked", true)

                        this.selectRows(hc ? i : indx[i]);

                    }

                }
            } 


In the above code example, the this.model.indexes additional property value is updated in both headCheckChange and checkChange, please refer to the highlighted section. We also modified the previously provided sample with the above code example and the same can be referred from the following link.

http://jsplayground.syncfusion.com/5bxpfhn0

Regards,
Madhu Sudhanan. P

Gomtesh
Replied On September 8, 2015 04:21 AM UTC

Hi Madhu,
solution your giving prperly,
Thanks a lot for giving solution

Madhu Sudhanan P [Syncfusion]
Replied On September 8, 2015 04:28 AM UTC

Hi Gomtesh,

Thanks for the update. We are happy that the requirement achieved.

Regards,
Madhu Sudhanan. P

CONFIRMATION

This post will be permanently deleted. Are you sure you want to continue?

Sorry, An error occured while processing your request. Please try again later.

Warning Icon You are using an outdated version of Internet Explorer that may not display all features of this and other websites. Upgrade to Internet Explorer 8 or newer for a better experience.Close Icon

;