This is famous code (thanks to @Nic). I see it everywhere
To make it even more robust:
- Tables in “Search” views should be supported (currently they aren’t)
- Certain rows should be skipped. For example, we probably don’t want checkboxes on a “group” row or “totals” rows.
Given the above, the updated function looks like this:
/*
Example Usage
Add checkboxes...
To a table: addCheckboxes(view)
To a table inside a Search View: addCheckboxes(view, 'search')
To all rows in a Search View: addCheckboxes(view, 'search', true)
To all rows in a Table View: addCheckboxes(view, 'table', true)
*/
function addCheckboxes(view, viewType='table', allRows=false) {
// Tables and search tables have slightly different css
let css
if (viewType == 'search') {
css = '.kn-search'
} else if (viewType == 'table') {
css = '.kn-table'
}
// Decide if we are including all rows (unlikely) or only record rows
const trCSS = allRows ? 'tr' : 'tr[id]'
// Add the checkbox to the header to select/unselect all
$('#' + view.key + css + ' thead tr').prepend('<th><input type="checkbox"></th>')
$('#' + view.key + css + ' thead input').change(function () {
$('.' + view.key + css + ' tbody tr input').each(function () {
$(this).attr('checked', $('#' + view.key + css + ' thead input').attr('checked') != undefined)
})
})
// Add a checkbox to each row in the table body
$('#' + view.key + css + ' tbody ' + trCSS).each(function () {
$(this).prepend('<td><input type="checkbox"></td>')
})
}
Of course, the rest of the code is the same (i.e. call the function inside the view-render
event and update your records).
Loving the community involvement on this snippet. Thanks everyone.
Ian
Knack Pros