I have a bunch of checkboxes that need to be toggled based on certain conditions. My function is called by multiple buttons on an onclick event. The certain condition is expressed as a string (check_all
, uncheck_all
, check_all_virtual
). The problem that I see is that if the function would be called as toggleCheckboxes('typo')
, that the error wouldn't be so easy to see as there would be no error message. Such problems should probably yield more information. How could this be done better?
<div>
<input name="site_ids[]" data-is-virtual="0" value="1" class="checkbox"/> SG3
<input name="site_ids[]" data-is-virtual="1" value="2" class="checkbox"/> SG1
<input name="site_ids[]" data-is-virtual="0" value="3" class="checkbox"/> SG2
</div>
<div>
<button onclick="toggleCheckboxes('check_all')">Check All</button>
<button onclick="toggleCheckboxes('uncheck_all')">Uncheck All</button>
<button onclick="toggleCheckboxes('check_all_virtual')">Check All Virtual</button>
</div>
<script type="text/javascript">
var checkboxes = document.getElementsByClassName('checkbox');
function toggleCheckboxes(operation) {
for (var i = 0, n = checkboxes.length; i < n; i++) {
switch (operation) {
case 'check_all':
checkboxes[i].checked = true;
break;
case 'uncheck_all':
checkboxes[i].checked = false;
break;
case 'check_all_virtual':
if (checkboxes[i].getAttribute('data-is-virtual') == true) {
checkboxes[i].checked = true;
}
break;
}
}
}
</script>
The functionality is correct. Checking all virtual shouldn't uncheck non-virtual.
for(var i = 0, n = checkboxes.length; i < n; i++)
be justfor(var i = 0; i < checkboxes.length; i++)
? The only reason I'd use the former, would be if I was aiming optimization (in case thecheckboxes.length
method was being called every iteration on the second code), but apparently on modern browsers both will only call it once if you don't change the length during the loop \$\endgroup\$ – IanC Nov 15 '16 at 13:28