Skip to content
Advertisement

Highlight selected jsGrid row

I found this example which highlights a row after it has been selected but the problem with it is that it keeps the previous row(s) highlighted after another one has been selected.

Here’s part of the code

//js
rowClick: function(args) {
        var $row = this.rowByItem(args.item);

      $row.toggleClass("highlight");
    }, 

//css
tr.highlight td.jsgrid-cell {
    background-color: green;
}

I can’t find a solution to unhighlight the previously selected row

Advertisement

Answer

You can achieve by this following steps

  1. First on row click you need to get selected row like this

    var selectedRow = $("#jsGrid").find('table tr.highlight').

  2. Then you can use

    selectedRow.toggleClass('highlight') or selectedRow.removeClass('highlight')

DEMO

$("#jsGrid").jsGrid({
    width: "100%",
    height: "auto",
    paging: false,

    //for loadData method Need to set auto load true
    autoload: true,

    noDataContent: "Directory is empty",

    controller: {
        loadData: function(filter) {
            var data = [{
                nickname: "Test",
                email: "t@gmail.com"
            }, {
                nickname: "Test 1",
                email: "t1@gmail.com"
            }, {
                nickname: "Test 2",
                email: "t2@gmail.com"
            }, {
                nickname: "Test 3",
                email: "t3@gmail.com"
            }];
            return data;
        }
    },

    rowClick: function(args) {
        var $row = this.rowByItem(args.item),
            selectedRow = $("#jsGrid").find('table tr.highlight');

        if (selectedRow.length) {
            selectedRow.toggleClass('highlight');
        };
        
        $row.toggleClass("highlight");
    },

    fields: [{
        name: "nickname",
        type: "text",
        width: 80,
        title: "Name"
    }, {
        name: "email",
        type: "text",
        width: 100,
        title: "Email Address",
        readOnly: false
    }]
});
tr.highlight td.jsgrid-cell {
  background-color: green;
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid-theme.min.css" />
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.js"></script>


<div id="jsGrid"></div>
Advertisement