jQuery DataTables: How to add a checkbox column

Example

Client-side processing mode with Ajax sourced data

Example below shows a data table in client-side processing mode where data is received from the server using Ajax.

Show
entries
Search:
Name Position Office Extn. Start date Salary

Name Position Office Extn. Start date Salary
Airi Satou Accountant Tokyo 5407 2008/11/28 $162,700
Angelica Ramos Chief Executive Officer (CEO) London 5797 2009/10/09 $1,200,000
Ashton Cox Junior Technical Author San Francisco 1562 2009/01/12 $86,000
Bradley Greer Software Engineer London 2558 2012/10/13 $132,000
Brenden Wagner Software Engineer San Francisco 1314 2011/06/07 $206,850
Brielle Williamson Integration Specialist New York 4804 2012/12/02 $372,000
Bruno Nash Software Engineer London 6222 2011/05/03 $163,500
Caesar Vance Pre-Sales Support New York 8330 2011/12/12 $106,450
Cara Stevens Sales Assistant New York 3990 2011/12/06 $145,600
Cedric Kelly Senior Javascript Developer Edinburgh 6224 2012/03/29 $433,060
Showing 1 to 10 of 57 entries
Previous 123456 Next



Data submitted to the server:

<table id="example" class="display select" cellspacing="0" width="100%"> <thead> <tr> <th><input name="select_all" value="1" id="example-select-all" type="checkbox"></th> <th>Name</th> <th>Position</th> <th>Office</th> <th>Extn.</th> <th>Start date</th> <th>Salary</th> </tr> </thead> <tfoot> <tr> <th></th> <th>Name</th> <th>Position</th> <th>Office</th> <th>Extn.</th> <th>Start date</th> <th>Salary</th> </tr> </tfoot> </table>



Highlights

Javascript
  • Columns definition

    'columnDefs': [{ 'targets': 0, 'searchable':false, 'orderable':false, 'className': 'dt-body-center', 'render': function (data, type, full, meta){ return '<input type="checkbox" name="id[]" value="' + $('<div/>').text(data).html() + '">'; } }],

Option columnsDef is used to define appearance and behavior of the first column ('targets': 0).

Searching and ordering of the column is not needed so this functionality is disabled with searchable and orderable options.

To center checkbox in the cell, internal DataTables CSS classdt-body-centeris used.

Option render is used to prepare the checkbox control for being displayed in each cell of the first column. We use a trick with$('<div/>').text(data).html()to encode HTML entities that could be present in the data.

Another trick here is to give input element a name with square brackets (id[]), this will make handling of list of checked checkboxes easier on the server-side. For example, PHP will convert all these parameters to an array, see PHP FAQ: How do I get all the results from a select multiple HTML tag for more information.

Initial sorting order

'order': [[1, 'asc']],

By default, DataTables sorts table by first column in ascending order. By using order option we select another column to perform initial sort.

“Select/deselect all” control

// Handle click on "Select all" control $('#example-select-all').on('click', function(){ // Get all rows with search applied var rows = table.rows({ 'search': 'applied' }).nodes(); // Check/uncheck checkboxes for all rows in the table $('input[type="checkbox"]', rows).prop('checked', this.checked); });

We attach event handler to handle clicks on “Select all” control. To retrieve all checkboxes that are present in the table taking into account currently applied filter, we use rows() method using appropriate selector-modifier.

// Handle click on checkbox to set state of "Select all" control $('#example tbody').on('change', 'input[type="checkbox"]', function(){ // If checkbox is not checked if(!this.checked){ var el = $('#example-select-all').get(0); // If "Select all" control is checked and has 'indeterminate' property if(el && el.checked && ('indeterminate' in el)){ // Set visual state of "Select all" control  // as 'indeterminate' el.indeterminate = true; } } });

The purpose of the event handler above is to detect when one of the checkboxes in the table is unchecked when “Select all” control was checked. When that happens, we can set “Select all” control to a special state indeterminate to indicate that not all checkboxes are checked.

Form submission

// Handle form submission event $('#frm-example').on('submit', function(e){ var form = this; // Iterate over all checkboxes in the table table.$('input[type="checkbox"]').each(function(){ // If checkbox doesn't exist in DOM if(!$.contains(document, this)){ // If checkbox is checked if(this.checked){ // Create a hidden element  $(form).append( $('<input>') .attr('type', 'hidden') .attr('name', this.name) .val(this.value) ); } } }); });
  • When table is enhanced by jQuery DataTables plug-in, only visible elements exist in DOM. That is why by default form submits checkboxes from current page only.

    To submit checkboxes from all pages we need to retrieve them with $() API method. Then for each checkbox not present in DOM we add a hidden element to the form with the same name and value. This allows all the data to be submitted.

    It’s even more simple if form submission is performed via Ajax. In that case URL-encoded data for submission can be produced using the code below:

    var data = table.$('input[type="checkbox"]').serialize();

Server-side processing

Please note that the example and code above will work for client-side processing mode only.

In server-side processing mode ('serverSide':true) elements<input type="checkbox">would exist for current page only. Once page is changed, the checked state of the checkboxes would not be preserved.

See jQuery DataTables – Row selection using checkboxes and Select extension for a universal solution that will work for server-side processing mode as well.

转载于:https://my.oschina.net/yygh/blog/656963

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值