Skip to content Skip to sidebar Skip to footer

How Do I Limit The Number Of Selected Choices In A Multi-select List Using Javascript?

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 th

Solution 1:

The clue is in the name of the first DOM object you call: getElementsByName

This returns a node list of all the elements with that name. You want to snip the first one off the list.

var selObj = document.getElementsByName('paramid[]')[0];

Better yet, rather than searching through the entire document:

var selObj = myForm.elements['paramid[]']

… where myForm is a reference to the form (which you could get from this if you used this function as a submit event handler).

Solution 2:

if its a simple javascript.. here you go.

<pre><html><script>functionhowMany() {
                 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");
                    returnfalse;
                 }
                 returntrue;
       }
        functiontestSubmit() {
            returnhowMany();
        }
    </script><body><formaction="http://google.com"><selectname="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><inputtype="submit"onclick="return testSubmit()"name="s"value=" How Many "id="s"/></form></body></html></pre>

Post a Comment for "How Do I Limit The Number Of Selected Choices In A Multi-select List Using Javascript?"