Welcome to WebmasterWorld Guest from 54.161.228.30

Forum Moderators: incrediBILL

Message Too Old, No Replies

restrict select multiple

   
9:36 am on Aug 9, 2011 (gmt 0)



Hi,

I was wondering if there is a way to restrict a <select multiple> listbox to maximum 2 options selected? Couldn't find an answer crawling the net..
11:41 am on Aug 9, 2011 (gmt 0)

WebmasterWorld Senior Member penders is a WebmasterWorld Top Contributor of All Time 5+ Year Member Top Contributors Of The Month



AFAIK there is no way to do this in HTML alone. You could perhaps use JavaScript to limit the number of selections. (Ultimately you will need to validate this in your server-side script.)
3:43 pm on Aug 9, 2011 (gmt 0)



thanks penders
7:47 am on Aug 10, 2011 (gmt 0)



Onclick you'll have to save the selections to an array, after the change of the selection, you count the array and if there are to many values, you reset the array to what it was before.....


<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>