Articles in this section
Category / Section

How to perform multiple row selection using checkbox in a Grid?

1 min read

By default, multiple selection is performed using the ctrl or shift key. You can also perform multiple selection by using Checkboxes that are bound to the JavaScript Grid rows or using the checkbox bound to the header.

Solution

The Checkbox can be bound to the Grid rows using the template property of the Grid and to the Grid header using the headerTemplateID property of the Grid. The template property is used to bind unbound column to the Grid. The headerTemplateID is used to add template within the header element.

Example

The following example explains in detail on how to perform multiple selection of records using Checkboxes.

  1. Code to render Checkbox.

JS

    <!--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>
  1. Render the Grid control.

JS

<div id="Grid"></div>
<script type="text/javascript">
    $(function () {// Document is ready.        
        $("#Grid").ejGrid({
            dataSource: window.gridData,
            allowSelection: true,
            selectionType: "multiple",
            allowPaging: true
            columns: [
                      { headerTemplateID: "#headerTemplate", template: true, templateID: "#checkboxTemplate", textAlign:ej.TextAlign.Center },//The checkbox column is bound to the grid using template property and headerTemplateID property
                      { field: "OrderID", headerText: "Order ID", isPrimaryKey: true, width: 100 },
                      { field: "CustomerID", headerText: "Customer ID", width: 130 },
                      { field: "Freight", headerText: "Freight", width: 100, format: "{0:C}" },
                      { field: "ShipCountry", headerText: "ShipCountry", width: 100 }
            ],
create: "create",
actionComplete: "complete",
recordClick: "recordClick"
    });
    });
</script>

MVC

[In View]
@(Html.EJ().Grid<object>("Grid")
      .Datasource((IEnumerable<object>)ViewBag.datasource)
      .AllowSelection()
      .SelectionType(SelectionType.Multiple)
      .AllowPaging()
      .Columns(col =>
        {
            col.HeaderTemplateID("#headerTemplate").Template(true).TemplateID("#checkboxTemplate").TextAlign(TextAlign.Center).Add();},//The checkbox column is bound to the grid using template property and headerTemplateID property
            col.Field("OrderID").HeaderText("Order ID").Width(75).Add();
            col.Field("CustomerID").HeaderText("Customer ID").Width(110).Add();
            col.Field("Freight").HeaderText("Freight").Width(75).Add();
            col.Field("ShipCountry").HeaderText("Ship Country").Width(110).Add();
      .ClientSideEvents(eve => eve.Create("create").ActionComplete("complete").RecordClick("recordClick"))
        })
)
 

ASP.NET

[aspx]
<ej:Grid ID="OrdersGrid" runat="server" AllowPaging="True" AllowSelection="True" Selectiontype="Multiple">  
            <ClientSideEvents Create="create" ActionComplete="complete" RecordClick="recordClick" />           
            <Columns>
                <ej:Column HeaderTemplateID="#headerTemplate" Template="True" TemplateID="#checkboxTemplate" TextAlign="Center" />},//The checkbox column is bound to the grid using template property and headerTemplateID property
                <ej:Column Field="OrderID" HeaderText="Order ID" IsPrimaryKey="True" />                
                <ej:Column Field="EmployeeID" HeaderText="Employee ID" />
                <ej:Column Field="Freight" HeaderText="Freight" Format="{0:C}" />                
                <ej:Column Field="ShipCity" HeaderText="Ship City" />
            </Columns>
</ej:Grid>  
 
  1. In the create and actionComplete events of the Grid, the change event of the Checkbox is triggered.

JS

function create(args){
        $("#Grid .rowCheckbox").ejCheckBox({ "change": checkChange });
         $("#headchk").ejCheckBox({ "change": headCheckChange });
   }
function complete(args) {
        $("#Grid .rowCheckbox").ejCheckBox({"change": checkChange});
         $("#headchk").ejCheckBox({ "change": headCheckChange, checked: false });
    }
  1. In the change event of the checkbox, the gridObj.multiSelectCtrlRequest is set as true in order to perform multiple selection.

JS

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
            }
  1. In the recordClick event of the Grid, the selected records are cleared and the Checkboxes corresponding to the selected records are unchecked.

JS

function recordClick(args) {
                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 });
                }
            }
  1. In the change event of the header checkbox (headerCheckChange), the grid contents are selected/unselected based on the header checkbox checked state.
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
                }
            }

 

The following screenshot displays the result.

Figure 1: Multiple selection in Grid using Checkboxes

Figure 2: Grid content is selected using the header checkbox


Conclusion

I hope you enjoyed learning about how to perform multiple row selection using checkbox in a Grid.

You can refer to our JavaScript Grid feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our JavaScript Grid example to understand how to create and manipulate data.

For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.

If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forumsDirect-Trac, or feedback portal. We are always happy to assist you!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments
Please sign in to leave a comment
Access denied
Access denied