Hi all,
Based on the JS code provided in the Developers section to "Add checkboxes to a table", I was wondering if anyone had developed any code to add a button in to delete all selected rows within that particular table?
Excellent thanks Stephen. Works a treat.
Does anyone have any code to copy selected records to a different object?
I've managed answered my own question. See below for the code I've merged with the existing 'Add checkboxes to a table' code (https://www.knack.com/developer-documentation/#add-checkboxes-to-a-table):
Structure:
Table view render
- Initialise addCheckboxes function
- Call addCheckboxes function
- Initialise deleteRecord function
- Listen for deleteRecords button click
HTML code for rich text to add button:
<input type="button" id="deleterecords" value="Delete Records">
Javascript code:
// Add checkboxes to a specific table view (view_6). Replace view_6 with your view key
$(document).on('knack-view-render.view_6', function (event, view) {
// Function that adds checkboxes
var addCheckboxes = function(view) {
// Add the checkbox to to the header to select/unselect all
$('#' + view.key + '.kn-table thead tr').prepend('<th style="width:10px;"><input type="checkbox"></th>');
$('#' + view.key + '.kn-table thead input').change(function() {
$('.' + view.key + '.kn-table tbody tr input').each(function() {
$(this).attr('checked', $('#' + view.key + '.kn-table thead input').attr('checked') != undefined);
});
});
// Add a checkbox to each row in the table body
$('#' + view.key + '.kn-table tbody tr').each(function() {
$(this).prepend('<td><input type="checkbox"></td>');
});
}
addCheckboxes(view); // Call the function to add
// Function to delete a specified record
function deleterecord(id)
{
$.ajax({
url: 'https://api.knack.com/v1/objects/object_1/records/' + id,
type: 'DELETE',
headers:
{
'X-Knack-Application-Id': "XXXXXX",
'X-Knack-REST-API-Key': "XXXXXX-XXXXXX-XXXXXX"
},
success: function(result)
{
location.hash = location.hash + "#";
}
});
}
$('#deleterecords').click( function () {
// Cycle through selected checkboxes. Use this in any code that needs to get the checked IDs
$('#view_6 tbody input[type=checkbox]:checked').each(function() {
var id = $(this).closest('tr').attr('id'); // record id
deleterecord(id);
});
});
});
You may want to add a confirm dialog for deletion.