Forum Moderators: open
<select name="test" size="7" multiple="multiple" onclick="saveSelected(this)" onchange="checkSelectedValues(this, 3)">
<option>123</option>
<option>456</option>
<option>789</option>
<option>987</option>
<option>654</option>
<option>321</option>
</select>
<script>
var selected = [];
function saveSelected(obj) {
// Before the new selectection, we save all the values
selected = [];
for(i=0;i<obj.options.length;i++) {
if(obj.options[i].selected) {
selected.push(i);
}
}
}
function checkSelectedValues(obj, max) {
// After selection we check the amount of selections
// And reset the selection if there are to many
if(selected.length >= max) {
alert("To many selected values");
// Uncheck all
for(i=0;i<obj.options.length;i++)
obj.options[i].selected = false
// Check the last known batch of options
for(i=0;i<selected.length;i++)
obj.options[ selected[i] ].selected = true;
}
}
</script>