patternjavascriptMinor
Counting thousands of selected checkboxes
Viewed 0 times
countingselectedthousandscheckboxes
Problem
This is a script I use to count how many items are selected in a form. It currently loops through the entire form to count how many check boxes are selected, each time a checkbox is clicked. The form has thousands of checkboxes, and it's painfully obvious how slow the script is with this many elements (About 18,240 items in my sample query).
Any ideas on how I can speed this up? The speed is fine when there's less than 1,000 results, but there's rarely that few when it's running in production.
Fun facts:
Any ideas on how I can speed this up? The speed is fine when there's less than 1,000 results, but there's rarely that few when it's running in production.
function countSelected()
{
var daform = document.forms.resultsForm;
var daspan = document.getElementById("acctSelected");
var counter = 0;
var i = 0;
if (daform.multi.length == undefined) {
if (daform.multi.checked) {
counter = "1";
} else {
counter = "0";
}
} else {
for (i = 0; i < daform.multi.length; i++)
{
if (daform.multi[i].checked) {
counter++;
}
}
}
daspan.innerHTML = counter;
}Fun facts:
- This script is fastest in Firefox 16.0.2 (about 2 secs)
- Second fastest by a slim margin in Internet Explorer 9 (about 2.25 secs)
- And absurdly slow in Chrome version 23.--- (I got tired of waiting)
Solution
I suspect you're going to struggle to optimise that, as DOM manipulation is always slow. See this guy's answer.
You could try do something like he suggests, keeping your data and the DOM separate from each other.
Currently it loops through the entire form to count how many check boxes are selected, each time a checkbox is clicked
Why not increment or decrement a counter when a checkbox's state is changed? That'll be a lot quicker.
You could try do something like he suggests, keeping your data and the DOM separate from each other.
Currently it loops through the entire form to count how many check boxes are selected, each time a checkbox is clicked
Why not increment or decrement a counter when a checkbox's state is changed? That'll be a lot quicker.
Context
StackExchange Code Review Q#18349, answer score: 5
Revisions (0)
No revisions yet.