How do I limit the number of selected choices in a multi-select list using JavaScript?
<p>I have <em>n</em> number of choices in a select box. After the user selects one or more choices in the select box and submits the form, I need to check that the user hasn't selected more than four choices.</p>

<p>I tried the following:</p>

<pre><code>function howMany() {
     var selObj = document.getElementsByName('xid[]');

     var totalChecked = 0;

     for (i = 0; i &lt; selObj.options.length; i++) {
         if (selObj.options[i].selected) {
             totalChecked++;
         }
     }
     if (totalChecked &gt; 4) {
        alert("You can't check more than 4 options");
        return false;
     }
     return true;
}
</code></pre>
