Skip to content

Instantly share code, notes, and snippets.

@adamboduch
Created July 30, 2013 14:23
Show Gist options
  • Save adamboduch/6113356 to your computer and use it in GitHub Desktop.
Save adamboduch/6113356 to your computer and use it in GitHub Desktop.
Use jquery.ui.selectable to select table rows. This example will sum the balance column based on the selected rows.
body {
margin: 1.4em;
}
table {
min-width: 30%;
}
table > thead > tr > td {
padding: 0.3em;
}
table > tbody > tr {
cursor: pointer;
}
.total {
margin: 1.2em 0;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI: Selectable Table Row</title>
<link href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" rel="stylesheet">
<link href="jquery.ui.selectable.table.row.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js" type="text/javascript"></script>
<script src="jquery.ui.selectable.table.row.js" type="text/javascript"></script>
</head>
<body>
<table class="ui-widget">
<thead class="ui-widget-header">
<tr>
<td>ID</td>
<td>Name</td>
<td>Balance</td>
</tr>
</thead>
<tbody class="ui-widget-content ui-state-default">
<tr>
<td>1</td>
<td>John</td>
<td>200</td>
</tr>
<tr>
<td>2</td>
<td>Mary</td>
<td>186</td>
</tr>
<tr>
<td>3</td>
<td>Bob</td>
<td>385</td>
</tr>
</tbody>
</table>
<div class="total ui-widget">
<strong>Total: </strong><span></span>
</div>
</body>
</html>
$(function() {
/*
* Updates the total span based on the selected table rows.
* Here, we're summing the balance column. This behavior is defined
* as a function here because it's used in several selectable event
* handlers below.
*
*/
function updateTotal( $selectees ) {
selected = $.makeArray( $selectees.filter( ".ui-selected" ) );
var total = selected.reduce( function( a, b ) {
return a + parseInt( $( b ).children( "td:last" ).text() );
}, 0 );
$( ".total > span " ).text( total );
}
$( "table > tbody" ).selectable({
// Don't allow individual table cell selection.
filter: ":not(td)",
// Update the initial total to 0, since nothing is selected yet.
create: function( e, ui ) {
updateTotal( $() );
},
// When a row is selected, add the highlight class to the row and
// update the total.
selected: function( e, ui ) {
$( ui.selected ).addClass( "ui-state-highlight" );
var widget = $( this ).data( "uiSelectable" );
updateTotal( widget.selectees );
},
// When a row is unselected, remove the highlight class from the row
// and update the total.
unselected: function( e, ui ) {
$( ui.unselected ).removeClass( "ui-state-highlight" );
var widget = $( this ).data( "uiSelectable" )
updateTotal( widget.selectees );
}
});
});
@Dosolutions
Copy link

This works great execpt only for whole numbers, no decimals...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment