tags:

views:

247

answers:

2

I have n 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.

I tried the following:

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

     var totalChecked = 0;

     for (i = 0; i < selObj.options.length; i++) {
         if (selObj.options[i].selected) {
             totalChecked++;
         }
     }
     if (totalChecked > 4) {
        alert("You can't check more than 4 options");
        return false;
     }
     return true;
}
+2  A: 
David Dorward
A: 

if its a simple javascript.. here you go.

<pre>
<html>
    <script>
        function howMany() {
                 var selObj = document.getElementById('paramid[]');
                 var totalChecked = 0;
                 for (i = 0; i < selObj.options.length; i++) {
                     if (selObj.options[i].selected) {
                         totalChecked++;
                     }
                 }
                 alert( totalChecked );
                 if (totalChecked > 4) {
                    alert("You can't check more than 4 options");
                    return false;
                 }
                 return true;
       }
        function testSubmit() {
            return howMany();
        }
    </script>
    <body>
        <form action="http://google.com"&gt;
            <select name="paramid[]" id="paramid[]" multiple>
                <option>TEST1</option
                <option>TEST2</option
                <option>TEST3</option
                <option>TEST4</option
                <option>TEST5</option
                <option>TEST6</option
                <option>TEST7</option
            </select>
            <input type="submit" onclick="return testSubmit()" name="s" value=" How Many " id="s"/>
        </form>
    </body>
</html>
</pre>
kadalamittai
Your formatting is broken, and you probably should mention that this requires the HTML to be modified (you should also fix it so it doesn't require the HTML be modified so that it is invalid, [ and ] are not allowed in id attributes in HTML).
David Dorward