TablixJS Selection & Custom Actions Demo

Interactive demonstration of row selection functionality with custom action buttons

How to Use Selection & Custom Actions:

Selection Controls

Custom Actions

Keyboard Shortcuts

Ctrl+A Select All | Escape Clear Selection | Delete Delete Selected

Selection Status:

No rows selected
{}

Documentation & Code Examples

Click the sections below to view implementation details and code examples for each feature.

🎯 Select All Rows Implementation

TablixJS now includes a built-in selectAllRows() method in the API for easy implementation:

Built-in API Method (Recommended):
// Method 1: Using built-in selectAllRows() API
const selectedCount = table.selectAllRows();
console.log(`Selected ${selectedCount} rows`);

// Method 2: With keyboard shortcut
document.addEventListener('keydown', (e) => {
    if (e.key === 'a' && (e.ctrlKey || e.metaKey)) {
        e.preventDefault();
        table.selectAllRows();
    }
});
Manual Implementation (Alternative):
// Alternative: Manual implementation using existing APIs
function selectAllRows() {
    const allData = table.getData();
    const allIds = allData.map(row => row.id.toString());
    table.selectRows(allIds);
}
HTML Button:
<button onclick="table.selectAllRows()">
    Select All Rows
</button>
💡 Tips:
  • table.selectAllRows() returns the number of rows selected
  • Only selects currently visible/filtered data (not hidden rows)
  • Triggers a custom 'selectAll' event with selected data
  • Works seamlessly with pagination - selects all data across pages
  • Respects current filters and search terms
  • Use dataIdKey option to specify which field to use as row ID

Custom Action Buttons

Create powerful custom actions that operate on selected rows:

Basic Custom Action Pattern:
// 1. Get selected data
const selectedData = table.getSelectedData();
const selectedIds = table.getSelectedIds();

// 2. Validate selection
if (selectedData.length === 0) {
    alert('No rows selected');
    return;
}

// 3. Process the data
selectedData.forEach((row, index) => {
    console.log(`Processing row ${index + 1}:`, row);
    // Your custom logic here
});

// 4. Update table if needed
table.loadData(updatedData);
Smart Button State Management:
// Update buttons when selection changes
table.eventManager.on('afterSelect', (event) => {
    const count = event.selectedData.length;
    updateActionButtons(count);
});

function updateActionButtons(selectedCount) {
    const buttons = ['exportBtn', 'deleteBtn', 'processBtn'];
    buttons.forEach(buttonId => {
        document.getElementById(buttonId).disabled = selectedCount === 0;
    });
}
💡 Available Selection APIs:
  • table.getSelectedData() - Array of selected row objects
  • table.getSelectedIds() - Array of selected row IDs
  • table.getSelectionCount() - Number of selected rows
  • table.isRowSelected(id) - Check if specific row is selected
  • table.clearSelection() - Clear all selections
  • table.selectAllRows() - Select all visible/filtered rows (NEW!)

🔗 PHP Server Integration

Send selected data to PHP scripts for server-side processing:

JavaScript - Send Data to PHP:
async function exportToPHP() {
    const selectedData = table.getSelectedData();
    
    try {
        const response = await fetch('/api/process-data.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                action: 'export_employees',
                data: selectedData,
                timestamp: new Date().toISOString()
            })
        });

        const result = await response.json();
        
        if (result.success) {
            alert(`Processed ${selectedData.length} rows successfully!`);
        }
    } catch (error) {
        console.error('Server error:', error);
    }
}
PHP - Receive and Process Data:
<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

try {
    $input = json_decode(file_get_contents('php://input'), true);
    
    if ($input['action'] === 'export_employees') {
        $selectedData = $input['selectedData'];
        
        // Process each selected row
        foreach ($selectedData as $employee) {
            // Save to database
            $stmt = $pdo->prepare("INSERT INTO processed_employees 
                (name, department, salary) VALUES (?, ?, ?)");
            $stmt->execute([
                $employee['name'], 
                $employee['department'], 
                $employee['salary']
            ]);
        }
        
        echo json_encode([
            'success' => true,
            'message' => 'Employees processed successfully',
            'count' => count($selectedData)
        ]);
    }
} catch (Exception $e) {
    echo json_encode([
        'success' => false, 
        'message' => $e->getMessage()
    ]);
}
?>
Integration Tips:
  • Always validate data on the server side
  • Use proper error handling and user feedback
  • Consider batch processing for large selections
  • Implement loading states for better UX

Keyboard Shortcuts Implementation

Add keyboard shortcuts to improve user experience:

Keyboard Event Handler:
document.addEventListener('keydown', (e) => {
    // Only handle when no input is focused
    const activeElement = document.activeElement;
    if (activeElement && (activeElement.tagName === 'INPUT' || 
                         activeElement.tagName === 'TEXTAREA')) {
        return;
    }
    
    switch (e.key) {
        case 'a':
        case 'A':
            if (e.ctrlKey || e.metaKey) {
                e.preventDefault();
                selectAllRows();
            }
            break;
            
        case 'Escape':
            e.preventDefault();
            table.clearSelection();
            break;
            
        case 'Delete':
            if (table.getSelectionCount() > 0) {
                deleteSelectedRows();
            }
            break;
    }
});
Display Shortcuts to Users:
<div class="keyboard-help">
    <p>
        <kbd>Ctrl+A</kbd> Select All | 
        <kbd>Escape</kbd> Clear Selection | 
        <kbd>Delete</kbd> Delete Selected
    </p>
</div>

<style>
kbd {
    background-color: #f8f9fa;
    border: 1px solid #ccc;
    border-radius: 3px;
    padding: 2px 5px;
    font-family: monospace;
}
</style>
💡 Best Practices:
  • Don't interfere with native browser shortcuts
  • Check if input fields are focused before handling
  • Provide visual feedback when shortcuts are used
  • Document shortcuts clearly for users
  • Test on different operating systems (Ctrl vs Cmd)