Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Wanet Telecoms Ltd on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Multiple Select 1

Status
Not open for further replies.

TheConeHead

Programmer
Aug 14, 2002
2,106
US
I have a multiple select that I want to have "None Selected" as the initial selected option. But I do not want people to be able to have "None Selected" and another value selected at the same time... I have the value for "None Selected" set to ""... How could I validate for this?

[conehead]
 
For the first question where you want "None Selected" to be the default, you could use the following function and call it on the onLoad event handler.

**** Assuming that "None Selected is your first item in the select box********

function setDefault(){
document.formname.selectboxname.options[0].selected=true;
}

To make sure "None Selected" is also selected with others

function checkSelection(){
if((document.formname.selectboxname.options[0].selected)&&(document.formname.selectboxname.options[1].selected||document.formname.selectboxname.options[2].selected||document.formname.selectboxname.options[3].selected)){
alert("You have selected \"None selected\" as well. you cannot proceed with this selection.");
document.formname.selectboxname.options[0].selected=false;
return false;
}
}

"Behind every great fortune there lies a great crime", Honore De Balzac
 
bnymk's solution will work fine if you only have 1 or 2 options in your select list. However, if you have 1000's you're not going to want to type out every possibility in the if condition. bnymk's solution accounts for a select list of 4 items and it already stretched the post, 1000's would be a nightmare.

Here's a solution that should work fine irregardless of the number of items in your select list. Additionally, the "none selected" option can appear anywhere in your list, it doesn't have to be the first (although 99% of the time it should be)
Code:
<script language="javascript">
function blah(a) {
   var blankFound = false;
   var cnt = 0; 
   for (i = 0; i < a.length; i++) {
      if(a.options[i].selected) {
         cnt++;
         blankFound = (a.options[i].value == '') || blankFound;
      }
   }
   if (blankFound && cnt > 1) {
      alert("You cannot \'none selected\' as part of a multiple selection")
      return false;
   }
   return true;
}
</script>
<select id=blah multiple>
<option value=''>none selected
<option value='1'>1
<option value='2'>2
<option value='3'>3
</select>
<input type=button value=test onclick="blah(document.getElementById('blah'))">

-kaht

...looks like you don't have a job, so why don't you get out there and feed Tina.
headbang.gif
[rockband]
headbang.gif
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top