Sunday, 28 February 2016

How to select multiple rows in a table.

In this example i will explain how to select multiple table rows by shift key by using Jquery.

<html>
<head></head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

<script>
$(document).ready(function(){

$("#tableStudent tr").click(function(){
$(this).toggleClass("selected"); // add or remove class to table row
var TotalTrs = $("#tableStudent").children('tbody').children('tr'); // getting the totle rows in a table
if (window.event.shiftKey) {
lastSelectedRow = this;
// if the current row index is less than the first selected row index then interchange  indexes
if(firstSelectedRow.rowIndex > lastSelectedRow.rowIndex)
{
lastSelectedRow.rowIndex = firstSelectedRow.rowIndex;
 firstSelectedRow.rowIndex= lastSelectedRow.rowIndex;
}
for(var i=  firstSelectedRow.rowIndex;i<= lastSelectedRow.rowIndex;i++)
{
TotalTrs [i-1].className="selected";
}
}

else {
firstSelectedRow=this;
}

});

});

</script>

<style>
.selected
{
background-color:red;
}
</style>



<table id="tableStudent" border="1">
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Class</th>
        </tr>
    </thead>
    <tbody>
        <tr >
            <td>1</td>
            <td>John</td>
            <td>4th</td>
        </tr>
         <tr >
            <td>2</td>
            <td>Jack</td>
            <td>5th</td>
        </tr>
         <tr >
            <td>3</td>
            <td>Michel</td>
            <td>6th</td>
        </tr>
        <tr >
            <td>4</td>
            <td>Mike</td>
            <td>7th</td>
        </tr>
        <tr >
            <td>5</td>
            <td>Yke</td>
            <td>8th</td>
        </tr>
         <tr >
            <td>6</td>
            <td>4ke</td>
            <td>9th</td>
        </tr>
        <tr >
            <td>7</td>
            <td>7ke</td>
            <td>10th</td>
        </tr>
    </tbody>
</table>
</body>
</html>