homepage Welcome to WebmasterWorld Guest from 23.20.220.61
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Pubcon Platinum Sponsor 2014
Home / Forums Index / Code, Content, and Presentation / HTML
Forum Library, Charter, Moderators: incrediBILL

HTML Forum

    
restrict select multiple
snehula




msg:4349416
 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




msg:4349433
 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:4349537
 3:43 pm on Aug 9, 2011 (gmt 0)

thanks penders

lostdreamer




msg:4349857
 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