jQuery DataTables – Row selection using checkboxes and Select extension
For more information, see https://www.gyrocode.com/projects/jquery-datatables-checkboxes/
by mamounothman
HTML
<link rel="stylesheet" href="https://cdn.datatables.net/v/dt/dt-1.10.16/sl-1.2.5/datatables.min.css">
<script src="https://cdn.datatables.net/v/dt/dt-1.10.16/sl-1.2.5/datatables.min.js"></script>
<link rel="stylesheet" href="//gyrocode.github.io/jquery-datatables-checkboxes/1.2.10/css/dataTables.checkboxes.css">
<script src="//gyrocode.github.io/jquery-datatables-checkboxes/1.2.10/js/dataTables.checkboxes.min.js"></script>
<h3><a href="https://www.gyrocode.com/projects/jquery-datatables-checkboxes/">jQuery DataTables Checkboxes</a></h3>
<a href="https://www.gyrocode.com/projects/jquery-datatables-checkboxes/">See full article on Gyrocode.com</a>
<hr><br>
<form id="frm-example" action="/path/to/your/script.php" method="POST">
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th></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>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
</table>
<hr>
<p>Press <b>Submit</b> and check console for URL-encoded form data that would be submitted.</p>
<p><button>Submit</button></p>
<p><b>Selected rows data:</b></p>
<pre id="example-console-rows"></pre>
<p><b>Form data as submitted to the server:</b></p>
<pre id="example-console-form"></pre>
</form>
JavaScript
$(document).ready(function() {
var table = $('#example').DataTable({
'ajax': 'https://gyrocode.github.io/files/jquery-datatables/arrays_id.json',
'columnDefs': [
{
'targets': 0,
'checkboxes': {
'selectRow': true
}
}
],
'select': {
'style': 'multi'
},
'order': [[1, 'asc']]
});
// Handle form submission event
$('#frm-example').on('submit', function(e){
var form = this;
var rows_selected = table.column(0).checkboxes.selected();
// Iterate over all selected checkboxes
$.each(rows_selected, function(index, rowId){
// Create a hidden element
$(form).append(
$('<input>')
.attr('type', 'hidden')
.attr('name', 'id[]')
.val(rowId)
);
});
table.api.cells().checkboxes.select();
// FOR DEMONSTRATION ONLY
// The code below is not needed in production
// Output form data to a console
$('#example-console-rows').text(rows_selected.join(","));
// Output form data to a console
$('#example-console-form').text($(form).serialize());
// Remove added elements
$('input[name="id\[\]"]', form).remove();
// Prevent actual form submission
e.preventDefault();
});
});