This is a script I use to count how many items are selected in a form. Currently it 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.
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 Fact:
- 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)
This is the solution I came up with based on the selected answer:
// To call the function from each checkbox...
onClick="countSelected(this.checked);"
// The function...
var counter = 0;
function countSelected(checked)
{
var daspan = document.getElementById("acctSelected");
if (checked) {
counter++;
} else {
counter--;
}
daspan.innerHTML = counter;
}
onchangeevent instead since there might be other ways for the user to check the checkbox other than clicking (i.e. keyboard). – crdx Nov 9 '12 at 8:14