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>
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">
<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>
Post a Comment for "How Do I Limit The Number Of Selected Choices In A Multi-select List Using JavaScript?"