Last active
April 26, 2017 04:02
-
-
Save cosmicbuffalo/8fcc2e066f78e3ad65b6d81ab89f2ade to your computer and use it in GitHub Desktop.
Javascipt and jQuery for adding multiple selection of table rows
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(document).ready(function(){ | |
//put all the table rows in a variable after page load to pass in to RowClick | |
var trs = $('#main-table tr') | |
//bind the click handler to all the table rows | |
$('tr').on('click', function(){ | |
//call the RowClick function on click event | |
RowClick($(this),false,trs) | |
}) | |
}) | |
//declare variable to store the most recently clicked row | |
var lastSelectedRow; | |
// disable text selection | |
document.onselectstart = function() { | |
return false; | |
} | |
function RowClick(currentrow, lock, rows) { | |
//if control is held down, toggle the row | |
if (window.event.ctrlKey) { | |
toggleRow(currentrow); | |
} | |
//if there are no buttons held down... | |
if (window.event.button === 0) { | |
//if neither control or shift are held down... | |
if (!window.event.ctrlKey && !window.event.shiftKey) { | |
//clear selection | |
clearAll(rows); | |
//toggle clicked row | |
toggleRow(currentrow); | |
} | |
//if shift is held down... | |
if (window.event.shiftKey) { | |
//pass the indexes of the last selected row and currently selected row along with all rows | |
selectRowsBetweenIndexes([lastSelectedRow.index(), currentrow.index()], rows) | |
} | |
} | |
} | |
function toggleRow(row) { | |
//if the row is not the header row... | |
if (!row.hasClass('header-row')){ | |
//if the row is selected... | |
if (row.hasClass('selected')){ | |
//deselect it | |
row.removeClass('selected') | |
} | |
else{ | |
//otherwise, select it | |
row.addClass('selected') | |
} | |
//reassign the most recently selected row | |
lastSelectedRow = row; | |
} | |
} | |
function selectRowsBetweenIndexes(indexes,rows) { | |
//sort the indexes in ascending order | |
indexes.sort(function(a, b) { | |
return a - b; | |
}); | |
//for every row starting at the first index, until the second index... | |
for (var i = indexes[0]; i <= indexes[1]; i++) { | |
//select the row | |
$(rows[i+1]).addClass('selected'); | |
} | |
} | |
function clearAll(rows) { | |
//for all rows... | |
for (var i = 0; i < rows.length; i++) { | |
//deselect each row | |
$(rows[i]).removeClass("selected"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment