homepage Welcome to WebmasterWorld Guest from 54.237.213.31
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member
Home / Forums Index / Code, Content, and Presentation / HTML
Forum Library, Charter, Moderators: incrediBILL

HTML Forum

    
restrict select multiple
snehula



 
Msg#: 4349414 posted 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..

 

penders

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



 
Msg#: 4349414 posted 11:41 am on Aug 9, 2011 (gmt 0)

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

snehula



 
Msg#: 4349414 posted 3:43 pm on Aug 9, 2011 (gmt 0)

thanks penders

lostdreamer



 
Msg#: 4349414 posted 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>

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / HTML
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved