drewbenn drewbenn - 1 year ago 61
Javascript Question

What's the most lightweight way to add onclick() to hundreds of checkboxes?

I have a web page, primarily used by mobile users (about 80% of my users), with about 350

<input type="checkbox">
elements. When a checkbox is checked or unchecked, I want to call some javascript to save the state in local storage. When I created my page there were only about 100 elements so instead of making each element
<input type="checkbox" onclick="save();">
which seemed prone to typos or just plain forgetting to add the
, I added this to my

var input_elements = document.querySelectorAll("input[type='checkbox']");
for (var i = 0; i < input_elements.length; i++) {
input_elements[i].addEventListener("click", function() { save(this); });

which works great but adds a small penalty to page load times -- which is getting worse as I add elements, and I'm expecting to keep adding another 100-150 each year.

Is there a "better" way of doing this, both in terms of reducing load times (especially for mobile users with slower browsers) and preventing me from making dumb typos that break something for my users but are hard for me to spot?

Answer Source

You can add event handler on some common parent, for example some wrapper div or document if there's no wrapper parent. Search for event delegation mechanism to get more information about this pattern.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download