如何简化并优化Blade模板中的jQuery复选框绑定代码?
Great question! Your current approach works, but binding an event handler to each individual checkbox is indeed redundant—especially if you have many sesi entries, this creates unnecessary duplicate handlers. The better approach here is to use event delegation, which lets you attach a single event handler to a parent element that will listen for events from its child elements (even if those children are added dynamically later).
Here's how to optimize your code:
Step 1: Update your jQuery code (remove the loop entirely)
Instead of looping through each sesi to bind the event, attach one handler to a static parent element (like the table that contains all your checkboxes). First, make sure your table has a unique identifier (e.g., add id="sesi-table" to your <table> tag if it doesn't already have one). Then replace your entire jQuery loop with this:
// Use event delegation on the table parent $('#sesi-table').on('change', '.switch-input', function() { if ($(this).is(':checked')) { console.log($(this).val()); // This will log the sesi ID, just like before } else { console.log('tidak checked'); } });
How this works:
- We attach the
changeevent listener to the static parent table (#sesi-table) instead of each checkbox. - The second argument
.switch-inputtells jQuery to only trigger the handler when the event originates from an element with that class (your checkboxes). - Inside the handler,
$(this)still refers to the specific checkbox that was toggled, so you can access itsvalueandcheckedstate just like before.
Key benefits:
- More efficient: Only one event handler is created instead of one per checkbox.
- Dynamic-friendly: If you ever add new
sesicheckboxes to the table later (via AJAX, for example), they'll automatically inherit the event handler without needing to re-bind anything. - Cleaner code: No need to loop through your
$sesiscollection in the jQuery section anymore.
Your HTML can stay exactly as it is—no changes needed there!
内容的提问来源于stack exchange,提问作者Fajar Alam

