I have a table where each row has a checkbox in it. I’ve added a simple JQuery function that makes the whole row clickable – when a user clicks anywhere within the row, it toggles the checkbox.
I’d like to be able to use these checkboxes with htmx, but it doesn’t seem to work. The HTMX network call seems to fire and function properly when clicking the checkbox itself, but clicking elsewhere in the row doesn’t trigger the API call or HTML replacement. Is there a way that I can get HTMX to work when clicking anywhere in the row?
Minimum reproducible example for the issue I’m seeing:
- JSFiddle: Table with clickable rows.
- JSFiddle: Attempt at using HTMX not working as desired. Note that in the console, an API call is only triggered when clicking the checkbox itself.
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>
<script src=" https://cdn.jsdelivr.net/npm/[email protected]/dist/htmx.min.js "></script>
</head>
<body>
<table class="table table-sm table-hover">
<thead>
<tr>
<th style="width: 30px"></th>
<th>Item</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr class="clickable">
<td>
<input
class="form-check-input"
type="checkbox"
id="item-1"
hx-get="/api/test"
hx-target="#target"
/>
</td>
<td>Widget</td>
<td>$10</td>
</tr>
<tr class="clickable">
<td>
<input
class="form-check-input"
type="checkbox"
id="item-2"
hx-get="/api/test"
hx-target="#target"
/>
</td>
<td>Big Widget</td>
<td>$15</td>
</tr>
<tr class="clickable">
<td>
<input
class="form-check-input"
type="checkbox"
id="item-3"
hx-get="/api/test"
hx-target="#target"
/>
</td>
<td>Heavy Widget</td>
<td>$12</td>
</tr>
</tbody>
</table>
<div id="target"></div>
<script>
$(document).ready(function () {
$("tr.clickable").on("click", function () {
var $checkbox = $(this).find("input:checkbox");
$checkbox.prop("checked", !$checkbox.prop("checked"));
});
$("tr.clickable > td > input:checkbox").on(
"click",
function (event) {
event.stopPropagation();
}
);
});
</script>
</body>
</html>
2
Answers
You can move the hx-get and hx-target to the
tr
element, so that all the child elements in the row will start making the api calls, as HTMX supports inheritance.And then define a function to check and uncheck the checkbox when clicking on row or checkbox.
Other then adding props, you also need to trigger
change
event on the checkbox.You can do that by using htmx’s trigger API: