Toggling checkboxes based on certain conditions 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?

&lt;div&gt;
    &lt;input name="site_ids[]" data-is-virtual="0" value="1" class="checkbox"/&gt; SG3
    &lt;input name="site_ids[]" data-is-virtual="1" value="2" class="checkbox"/&gt; SG1
    &lt;input name="site_ids[]" data-is-virtual="0" value="3" class="checkbox"/&gt; SG2
&lt;/div&gt;
&lt;div&gt;
    &lt;button onclick="toggleCheckboxes('check_all')"&gt;Check All&lt;/button&gt;
    &lt;button onclick="toggleCheckboxes('uncheck_all')"&gt;Uncheck All&lt;/button&gt;
    &lt;button onclick="toggleCheckboxes('check_all_virtual')"&gt;Check All Virtual&lt;/button&gt;
&lt;/div&gt;

&lt;script type="text/javascript"&gt;
var checkboxes = document.getElementsByClassName('checkbox');

function toggleCheckboxes(operation) {
    for (var i = 0, n = checkboxes.length; i &lt; 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;
        }
    }
}
&lt;/script&gt;


The functionality is correct. Checking all virtual shouldn't uncheck non-virtual.
I may have misunderstood something but if you just want to be able to detect case where the input string is none of expected, you may do something like that:

default:
  console.log("This operation '"+operation+"' is not supported, it will be ignored");


at the end of your switch\case construction