DHTMLX Docs & Samples Explorer

Index
dhtmlxgrid

## Step 7 - Event Handlers

Like with any other component you need to have the ability to set your own reaction on some user action. For example, you need something to be done when a user clicks on a row in grid. dhtmlxGrid provides this possibility together with impressive list of events.

The way of setting event handler is common for all events. Just call attachEvent method of the grid object with the event name as the first argument and the event handler function as the second argument. Depending on the event, an event handler will get various number of incoming parameters. For example, onRowSelect event handler will get 2 incoming parameters: row ID and cell index where user clicked to the select row:

        function doOnRowSelected(rowID,celInd){
            alert("Selected row ID is "+rowID+"\nUser clicked cell with index "+celInd);

        }
        mygrid.attachEvent("onRowSelect",doOnRowSelected);

### Resulting code

Here is what we get at the end:

        <title>dhtmlxGrid Sample Page</title>

         <link rel="STYLESHEET" type="text/css" href="codebase/dhtmlxgrid.css">
         <script src="codebase/dhtmlxcommon.js"></script>
         <script src="codebase/dhtmlxgrid.js"></script>
         <script src="codebase/dhtmlxgridcell.js"></script>

         <script>
          var mygrid;
          function doInitGrid(){
           mygrid = new dhtmlXGridObject('mygrid_container');
           mygrid.setImagePath("codebase/imgs/");
           mygrid.setHeader("Model,Qty,Price");
           mygrid.setInitWidths("*,150,150");
           mygrid.setColAlign("left,right,right")
           mygrid.setSkin("light");
           mygrid.setColSorting("str,int,int");
           mygrid.setColTypes("ed,ed,price");
           mygrid.attachEvent("onRowSelect",doOnRowSelected);
           mygrid.init();
           mygrid.loadXML("step3.xml");
          }

          function addRow(){
           var newId = (new Date()).valueOf()
           mygrid.addRow(newId,"",mygrid.getRowsNum())
           mygrid.selectRow(mygrid.getRowIndex(newId),false,false,true);
          }
          function removeRow(){
           var selId = mygrid.getSelectedId()
           mygrid.deleteRow(selId);
          }

          function doOnRowSelected(rowID,celInd){
           alert("Selected row ID is "+rowID+"\nUser clicked cell with index "+celInd);
          }

         </script>

         <body onload="doInitGrid()">
          <div id="mygrid_container" style="width:600px;height:150px;"></div>
         </body>