如何在HTMX中按类名从项目列表获取ID
Using HTMX to Send Selected Table Row IDs to Your PHP Script
No problem—here's a clean, straightforward way to handle this with HTMX, leveraging its ability to run JavaScript functions dynamically when triggering requests:
Step 1: Set Up Your HTML
First, your table rows and a trigger button (could be any element, but a button makes sense here):
<!-- Your table with selected rows --> <table> <tr id="itemid-1234" class="selected">...</tr> <tr id="itemid-5678">...</tr> <tr id="itemid-9012" class="selected">...</tr> </table> <!-- HTMX trigger button --> <button hx-post="/path/to/your-script.php" hx-vals='js:{selectedIds: getSelectedItemIds()}' hx-target="#response-area" hx-swap="innerHTML"> Submit Selected Items </button> <!-- Optional: Area to show response --> <div id="response-area"></div>
Step 2: Add the JavaScript Function to Collect IDs
This function grabs all selected rows, extracts the numeric part from their itemid-* IDs, and returns them as an array:
function getSelectedItemIds() { // Get all <tr> elements with "selected" class and ID starting with "itemid-" const selectedRows = document.querySelectorAll('tr.selected[id^="itemid-"]'); // Convert NodeList to array, then extract the numeric ID part return Array.from(selectedRows).map(row => { // Split the ID on "-" and take the second part (the number) return row.id.split('-')[1]; }); }
Step 3: Handle the Request in PHP
HTMX will send the selected IDs as a POST parameter array. In your PHP script, you can access them directly:
<?php // Get the array of selected IDs (fallback to empty array if not present) $selectedIds = $_POST['selectedIds'] ?? []; // Do something with the IDs (e.g., database operations, validation) foreach ($selectedIds as $id) { // Process each ID... } // Send a response back (optional) echo "Successfully processed " . count($selectedIds) . " selected items."; ?>
How It Works
- When you click the button, HTMX runs the
getSelectedItemIds()function specified inhx-vals. - The function returns an array of numeric IDs, which HTMX automatically encodes into the POST request (formatted as
selectedIds[]=1234&selectedIds[]=9012). - Your PHP script receives the array and can process it as needed.
Bonus: Add Loading State (Optional)
You can easily add a loading indicator using HTMX's built-in attributes for better UX:
<button hx-post="/path/to/your-script.php" hx-vals='js:{selectedIds: getSelectedItemIds()}' hx-target="#response-area" hx-swap="innerHTML" hx-indicator="#loading-spinner"> Submit Selected Items </button> <div id="loading-spinner" class="htmx-indicator">Processing...</div>
内容的提问来源于stack exchange,提问作者Simon
相关产品推荐
相关产品推荐

