<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Example: Checkbox select column</title>
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=PT+Sans:400,700,400italic,700italic">
<link rel="stylesheet" href="../../build/cssgrids/cssgrids-min.css">
<link rel="stylesheet" href="../assets/css/main.css">
<link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
<link rel="shortcut icon" type="image/png" href="../assets/favicon.png">
<script src="../../build/yui/yui-min.js"></script>
</head>
<body>
<!--
<a href="https://github.com/yui/yui3"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png" alt="Fork me on GitHub"></a>
-->
<div id="doc">
<div id="hd">
<h1><img src="http://yuilibrary.com/img/yui-logo.png"></h1>
</div>
<h1>Example: Checkbox select column</h1>
<div class="yui3-g">
<div class="yui3-u-3-4">
<div id="main">
<div class="content"><style scoped>
/* css to counter global site css */
.example table {
width: auto;
}
.yui3-skin-sam .yui3-datatable-col-select {
text-align: center;
}
#processed {
margin-top: 2em;
border: 2px inset;
border-radius: 5px;
padding: 1em;
list-style: none;
}
</style>
<div class="intro">
<p>
This example shows one method for managing a selection checkbox column
in a DataTable.
</p>
</div>
<div class="example yui3-skin-sam">
<div id="dtable"></div>
<button id="btnSelected" class="yui3-button">Process Selections</button>
<button id="btnClearSelected" class="yui3-button">Clear Selections</button>
<h4>Processed:</h4>
<ul id="processed">
<li>(None)</li>
</ul>
</div>
<script>
YUI({ filter: 'raw' }).use( "datatable-sort", "datatable-scroll", "cssbutton", function (Y) {
var ports = [
{ port:20, pname:'FTP_data',ptitle:'File Transfer Process Data' },
{ port:21, pname:'FTP', ptitle:'File Transfer Process' },
{ port:22, pname:'SSH', ptitle:'Secure Shell' },
{ port:23, pname:'TELNET', ptitle:'Telnet remote communications' },
{ port:25, pname:'SMTP', ptitle:'Simple Mail Transfer Protocol' },
{ port:43, pname:'WHOIS', ptitle:'whois Identification' },
{ port:53, pname:'DNS', ptitle:'Domain Name Service' },
{ port:68, pname:'DHCP', ptitle:'Dynamic Host Control Protocol' },
{ port:79, pname:'FINGER', ptitle:'Finger Identification' },
{ port:80, pname:'HTTP', ptitle:'HyperText Transfer Protocol' },
{ port:110, pname:'POP3', ptitle:'Post Office Protocol v3' },
{ port:115, pname:'SFTP', ptitle:'Secure File Transfer Protocol' },
{ port:119, pname:'NNTP', ptitle:'Network New Transfer Protocol' },
{ port:123, pname:'NTP', ptitle:'Network Time Protocol' },
{ port:139, pname:'NetBIOS',ptitle:'NetBIOS Communication' },
{ port:143, pname:'IMAP', ptitle:'Internet Message Access Protocol' },
{ port:161, pname:'SNMP', ptitle:'Simple Network Management Protocol' },
{ port:194, pname:'IRC', ptitle:'Internet Relay Chat' },
{ port:220, pname:'IMAP3', ptitle:'Internet Message Access Protocol v3' },
{ port:389, pname:'LDAP', ptitle:'Lightweight Directory Access Protocol' },
{ port:443, pname:'SSL', ptitle:'Secure Socket Layer' },
{ port:445, pname:'SMB', ptitle:'NetBIOS over TCP' },
{ port:993, pname:'SIMAP', ptitle:'Secure IMAP Mail' },
{ port:995, pname:'SPOP', ptitle:'Secure POP Mail' }
];
var table = new Y.DataTable({
columns : [
{ key: 'select',
allowHTML: true, // to avoid HTML escaping
label: '<input type="checkbox" class="protocol-select-all" title="Toggle ALL records"/>',
formatter: '<input type="checkbox" checked/>',
emptyCellValue: '<input type="checkbox"/>'
},
{ key: 'port', label: 'Port No.' },
{ key: 'pname', label: 'Protocol' },
{ key: 'ptitle', label: 'Common Name' }
],
data : ports,
scrollable: 'y',
height : '250px',
sortable : ['port','pname'],
sortBy : 'port',
recordType: ['select', 'port', 'pname', 'ptitle']
}).render("#dtable");
// To avoid checkbox click causing harmless error in sorting
// Workaround for bug #2532244
table.detach('*:change');
//----------------
// "checkbox" Click listeners ...
//----------------
// Define a listener on the DT first column for each record's "checkbox",
// to set the value of <code>select</code> to the checkbox setting
table.delegate("click", function(e){
// undefined to trigger the emptyCellValue
var checked = e.target.get('checked') || undefined;
this.getRecord(e.target).set('select', checked);
// Uncheck the header checkbox
this.get('contentBox')
.one('.protocol-select-all').set('checked', false);
}, ".yui3-datatable-data .yui3-datatable-col-select input", table);
// Also define a listener on the single TH "checkbox" to
// toggle all of the checkboxes
table.delegate('click', function (e) {
// undefined to trigger the emptyCellValue
var checked = e.target.get('checked') || undefined;
// Set the selected attribute in all records in the ModelList silently
// to avoid each update triggering a table update
this.data.invoke('set', 'select', checked, { silent: true });
// Update the table now that all records have been updated
this.syncUI();
}, '.protocol-select-all', table);
//----------------
// CSS-Button click handlers ....
//----------------
function process() {
var ml = table.data,
msg = '',
template = '<li>Record index = {index} Data = {port} : {pname}</li>';
ml.each(function (item, i) {
var data = item.getAttrs(['select', 'port', 'pname']);
if (data.select) {
data.index = i;
msg += Y.Lang.sub(template, data);
}
});
Y.one("#processed").setHTML(msg || '<li>(None)</li>');
}
Y.one("#btnSelected").on("click", process);
Y.one("#btnClearSelected").on("click",function () {
table.data.invoke('set', 'select', undefined);
// Uncheck the header checkbox
table.get('contentBox')
.one('.protocol-select-all').set('checked', false);
process();
});
});
</script>
<h2>Sample Data</h2>
<p>
This example will use a local Javascript array of data that includes some
common Internet port socket numbers and protocol names:
</p>
<pre class="code prettyprint">var ports = [
{ port:20, pname:'FTP_data',ptitle:'File Transfer Process Data' },
{ port:21, pname:'FTP', ptitle:'File Transfer Process' },
{ port:22, pname:'SSH', ptitle:'Secure Shell' },
{ port:23, pname:'TELNET', ptitle:'Telnet remote communications' },
... // data continues
];</pre>
<h2>The DataTable</h2>
<p>
Our DataTable for this example will utilize a custom formatter as the first
column, to display a standard HTML INPUT[type=checkbox] element as an
indication that the record is desired to be "selected" for additional
processing. But that checkbox won't work on its own, because if a "sort"
action happens after the checkbox is clicked the "check" status is lost!
</p>
<p>
A way to get around this is to create a binding of the checkbox to an
attribute of <b>each record</b> which will remain with the record even upon
sorts, edits, or other modifications to the record. This is accomplished
by defining a custom <code>recordType</code> for the DataTable that incorporates all
of our standard <code>data</code> for our table but also defines a new Attribute
(called <code>select</code> here) that is a boolean value to track whether the record
is selected.
</p>
<p>
The implementation of these methods is shown below, where we have defined a
custom <code>formatter</code> and <code>emptyCellValue</code> for the "select" column that
creates a checked or unchecked checkbox depending on the state of the
attribute, and defines a custom <code>recordType</code> with our new attribute added.
Additionally, we incorporate (a) scrolling and (b) sorting to demonstrate
that this technique works.
</p>
<pre class="code prettyprint">var table = new Y.DataTable({
columns : [
{ key: 'select',
allowHTML: true, // to avoid HTML escaping
label: '<input type="checkbox" class="protocol-select-all" title="Toggle ALL records"/>',
formatter: '<input type="checkbox" checked/>',
emptyCellValue: '<input type="checkbox"/>'
},
{ key: 'port', label: 'Port No.' },
{ key: 'pname', label: 'Protocol' },
{ key: 'ptitle', label: 'Common Name' }
],
data : ports,
scrollable: 'y',
height : '250px',
sortable : ['port','pname'],
sortBy : 'port',
recordType: ['select', 'port', 'pname', 'ptitle']
}).render("#dtable");</pre>
<h2>The Checkbox Listeners</h2>
<p>
Having a DataTable with a bunch of checkboxes in it may look cool (or
not!), but we also need to define what to do when they are checked. Since
the column formatter for the first column creates the checkboxes, we
delegate "click" listeners from the DataTable for the two types of
checkboxes—the "check all" checkbox in the header and the individual
checkboxes on each data row.
</p>
<p>
Be sure to <a href="../event/delegation.html">avoid subscribing to events
directly on elements in each row</a> of a DataTable.
</p>
<pre class="code prettyprint">// Define a listener on the DT first column for each record's checkbox,
// to set the value of `select` to the checkbox setting
table.delegate("click", function(e){
// undefined to trigger the emptyCellValue
var checked = e.target.get('checked') || undefined;
this.getRecord(e.target).set('select', checked);
// Uncheck the header checkbox
this.get('contentBox')
.one('.protocol-select-all').set('checked', false);
}, ".yui3-datatable-data .yui3-datatable-col-select input", table);
// Also define a listener on the single TH checkbox to
// toggle all of the checkboxes
table.delegate('click', function (e) {
// undefined to trigger the emptyCellValue
var checked = e.target.get('checked') || undefined;
// Set the selected attribute in all records in the ModelList silently
// to avoid each update triggering a table update
this.data.invoke('set', 'select', checked, { silent: true });
// Update the table now that all records have been updated
this.syncUI();
}, '.protocol-select-all', table);</pre>
<h2>Button Click Handlers</h2>
<p>
The bulk of the nitty-gritty is done now. We'll just wire up a button to
process the checked records and another to clear the selection.
</p>
<pre class="code prettyprint">function process() {
var ml = table.data,
msg = '',
template = '<li>Record index = {index} Data = {port} : {pname}</li>';
ml.each(function (item, i) {
var data = item.getAttrs(['select', 'port', 'pname']);
if (data.select) {
data.index = i;
msg += Y.Lang.sub(template, data);
}
});
Y.one("#processed").setHTML(msg || '<li>(None)</li>');
}
Y.one("#btnSelected").on("click", process);
Y.one("#btnClearSelected").on("click",function () {
table.data.invoke('set', 'select', undefined);
// Uncheck the header checkbox
table.get('contentBox')
.one('.protocol-select-all').set('checked', false);
process();
});</pre>
<p>
Note that another option for capturing all the checked checkboxes would be
<code>table.get('contentBox').all('.yui3-datatable-col-select input:checked')</code>.
To make sure that was supported across all browsers, we'd then need to
include the <code>selector-css3</code> module in our <code>use()</code> statement.
</p>
<p>
Another improvement that could be made for HTML5 compliant clients would be
to add in <code>localStorage</code> access to save the checked record data to the
browser environment. You can see how to do this in the
<a href="../app/app-todo.html">App Framework's Todo List example</a>.
</p>
<h2>Full Code Listing</h2>
<h3>CSS</h3>
<pre class="code prettyprint">.yui3-skin-sam .yui3-datatable-col-select {
text-align: center;
}
#processed {
margin-top: 2em;
border: 2px inset;
border-radius: 5px;
padding: 1em;
list-style: none;
}</pre>
<h3>HTML Markup</h3>
<p>
<strong>Note:</strong> be sure to add the <code>yui3-skin-sam</code> classname to the
page's <code><body></code> element or to a parent element of the widget in order to apply
the default CSS skin. See <a href="http://yuilibrary.com/yui/docs/tutorials/skins/">Understanding Skinning</a>.
</p>
<pre class="code prettyprint"><div class="example yui3-skin-sam"> <!-- You need this skin class -->
<div id="dtable"></div>
<button id="btnSelected" class="yui3-button">Process Selections</button>
<button id="btnClearSelected" class="yui3-button">Clear Selections</button>
<h4>Processed:</h4>
<ul id="processed">
<li>(None)</li>
</ul>
</div></pre>
<h3>Javascript</h3>
<pre class="code prettyprint">YUI({ filter: 'raw' }).use( "datatable-sort", "datatable-scroll", "cssbutton", function (Y) {
var ports = [
{ port:20, pname:'FTP_data',ptitle:'File Transfer Process Data' },
{ port:21, pname:'FTP', ptitle:'File Transfer Process' },
{ port:22, pname:'SSH', ptitle:'Secure Shell' },
{ port:23, pname:'TELNET', ptitle:'Telnet remote communications' },
{ port:25, pname:'SMTP', ptitle:'Simple Mail Transfer Protocol' },
{ port:43, pname:'WHOIS', ptitle:'whois Identification' },
{ port:53, pname:'DNS', ptitle:'Domain Name Service' },
{ port:68, pname:'DHCP', ptitle:'Dynamic Host Control Protocol' },
{ port:79, pname:'FINGER', ptitle:'Finger Identification' },
{ port:80, pname:'HTTP', ptitle:'HyperText Transfer Protocol' },
{ port:110, pname:'POP3', ptitle:'Post Office Protocol v3' },
{ port:115, pname:'SFTP', ptitle:'Secure File Transfer Protocol' },
{ port:119, pname:'NNTP', ptitle:'Network New Transfer Protocol' },
{ port:123, pname:'NTP', ptitle:'Network Time Protocol' },
{ port:139, pname:'NetBIOS',ptitle:'NetBIOS Communication' },
{ port:143, pname:'IMAP', ptitle:'Internet Message Access Protocol' },
{ port:161, pname:'SNMP', ptitle:'Simple Network Management Protocol' },
{ port:194, pname:'IRC', ptitle:'Internet Relay Chat' },
{ port:220, pname:'IMAP3', ptitle:'Internet Message Access Protocol v3' },
{ port:389, pname:'LDAP', ptitle:'Lightweight Directory Access Protocol' },
{ port:443, pname:'SSL', ptitle:'Secure Socket Layer' },
{ port:445, pname:'SMB', ptitle:'NetBIOS over TCP' },
{ port:993, pname:'SIMAP', ptitle:'Secure IMAP Mail' },
{ port:995, pname:'SPOP', ptitle:'Secure POP Mail' }
];
var table = new Y.DataTable({
columns : [
{ key: 'select',
allowHTML: true, // to avoid HTML escaping
label: '<input type="checkbox" class="protocol-select-all" title="Toggle ALL records"/>',
formatter: '<input type="checkbox" checked/>',
emptyCellValue: '<input type="checkbox"/>'
},
{ key: 'port', label: 'Port No.' },
{ key: 'pname', label: 'Protocol' },
{ key: 'ptitle', label: 'Common Name' }
],
data : ports,
scrollable: 'y',
height : '250px',
sortable : ['port','pname'],
sortBy : 'port',
recordType: ['select', 'port', 'pname', 'ptitle']
}).render("#dtable");
// To avoid checkbox click causing harmless error in sorting
// Workaround for bug #2532244
table.detach('*:change');
//----------------
// "checkbox" Click listeners ...
//----------------
// Define a listener on the DT first column for each record's "checkbox",
// to set the value of `select` to the checkbox setting
table.delegate("click", function(e){
// undefined to trigger the emptyCellValue
var checked = e.target.get('checked') || undefined;
this.getRecord(e.target).set('select', checked);
// Uncheck the header checkbox
this.get('contentBox')
.one('.protocol-select-all').set('checked', false);
}, ".yui3-datatable-data .yui3-datatable-col-select input", table);
// Also define a listener on the single TH "checkbox" to
// toggle all of the checkboxes
table.delegate('click', function (e) {
// undefined to trigger the emptyCellValue
var checked = e.target.get('checked') || undefined;
// Set the selected attribute in all records in the ModelList silently
// to avoid each update triggering a table update
this.data.invoke('set', 'select', checked, { silent: true });
// Update the table now that all records have been updated
this.syncUI();
}, '.protocol-select-all', table);
//----------------
// CSS-Button click handlers ....
//----------------
function process() {
var ml = table.data,
msg = '',
template = '<li>Record index = {index} Data = {port} : {pname}</li>';
ml.each(function (item, i) {
var data = item.getAttrs(['select', 'port', 'pname']);
if (data.select) {
data.index = i;
msg += Y.Lang.sub(template, data);
}
});
Y.one("#processed").setHTML(msg || '<li>(None)</li>');
}
Y.one("#btnSelected").on("click", process);
Y.one("#btnClearSelected").on("click",function () {
table.data.invoke('set', 'select', undefined);
// Uncheck the header checkbox
table.get('contentBox')
.one('.protocol-select-all').set('checked', false);
process();
});
});</pre>
</div>
</div>
</div>
<div class="yui3-u-1-4">
<div class="sidebar">
<div class="sidebox">
<div class="hd">
<h2 class="no-toc">Examples</h2>
</div>
<div class="bd">
<ul class="examples">
<li data-description="This example illustrates simple DataTable use cases.">
<a href="datatable-basic.html">Basic DataTable</a>
</li>
<li data-description="DataTable loaded with JSON data from a remote webservice via DataSource.Get">
<a href="datatable-dsget.html">DataTable + DataSource.Get + JSON Data</a>
</li>
<li data-description="DataTable loaded with XML data from a remote webservice via DataSource.IO.">
<a href="datatable-dsio.html">DataTable + DataSource.IO + XML Data</a>
</li>
<li data-description="Custom format data for display.">
<a href="datatable-formatting.html">Formatting Row Data for Display</a>
</li>
<li data-description="DataTable with nested column headers.">
<a href="datatable-nestedcols.html">Nested Column Headers</a>
</li>
<li data-description="DataTable with column sorting.">
<a href="datatable-sort.html">Column Sorting</a>
</li>
<li data-description="DataTable with vertical and/or horizontal scrolling rows.">
<a href="datatable-scroll.html">Scrolling DataTable</a>
</li>
<li data-description="Using DataTable's recordType attribute to create calculated, sortable columns.">
<a href="datatable-recordtype.html">Sortable generated columns</a>
</li>
<li data-description="Populating one DataTable from details in the data of another.">
<a href="datatable-masterdetail.html">Master and detail tables</a>
</li>
<li data-description="Checkbox column that retains checked state when sorting.">
<a href="datatable-chkboxselect.html">Checkbox select column</a>
</li>
</ul>
</div>
</div>
<div class="sidebox">
<div class="hd">
<h2 class="no-toc">Examples That Use This Component</h2>
</div>
<div class="bd">
<ul class="examples">
<li data-description="Shows how to instantiate multiple Panel instances, and use nested modality to interact with a Datatable.">
<a href="../panel/panel-form.html">Creating a Modal Form</a>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="../assets/vendor/prettify/prettify-min.js"></script>
<script>prettyPrint();</script>
<script>
YUI.Env.Tests = {
examples: [],
project: '../assets',
assets: '../assets/datatable',
name: 'datatable-chkboxselect',
title: 'Checkbox select column',
newWindow: '',
auto: false
};
YUI.Env.Tests.examples.push('datatable-basic');
YUI.Env.Tests.examples.push('datatable-dsget');
YUI.Env.Tests.examples.push('datatable-dsio');
YUI.Env.Tests.examples.push('datatable-formatting');
YUI.Env.Tests.examples.push('datatable-nestedcols');
YUI.Env.Tests.examples.push('datatable-sort');
YUI.Env.Tests.examples.push('datatable-scroll');
YUI.Env.Tests.examples.push('datatable-recordtype');
YUI.Env.Tests.examples.push('datatable-masterdetail');
YUI.Env.Tests.examples.push('datatable-chkboxselect');
YUI.Env.Tests.examples.push('panel-form');
</script>
<script src="../assets/yui/test-runner.js"></script>
</body>
</html>