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 Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Check for number of selects 1

Status
Not open for further replies.

soulpumpkin

Programmer
Feb 18, 2005
79
0
0
US
I'm not very versed in JavaScript, and I'm having trouble getting the below code to work. It should test to make sure only a single selection was made, but it isn't working:

Code:
function validateForm(varFormAction){
   var formValidated = true;
   //check to make sure one is selected
   if(varFormAction == "OpenSim"){
      if(document.forms[0].SimList.selectedIndex == -1){
         alert("Please choose a simulation.");
         formValidated = false;		
      }
   }
   //check to see if only one is selected
   if(document.forms[0].SimList.options.length > 1){
      alert("Please choose a single simulation.");
      formValidated = false;		
   }		
}

Could someone point me in the right direction?

Soul Pumpkin
 
If you want to make sure no more than one option is selected, the obvious way is to make it an select-one element. Apart from that, if you want js function to examine that fact, you can do this.
[tt]
function validateForm(varFormAction){
var formValidated = true;
//check to make sure one is selected
if(varFormAction == "OpenSim"){
if(document.forms[0].SimList.selectedIndex == -1){
alert("Please choose a simulation.");
formValidated = false;
}
}
//check to see if only one is selected
[blue]var ichosen=0;[/blue]
//if(document.forms[0].SimList.options.length > 1){
[blue]for (var i=0;i<document.forms[0].SimList.length;i++) {
if (document.forms[0].SimList.options.selected) {
ichosen++;
}
}
if (ichosen>1) {[/blue]
alert("Please choose a single simulation.");
formValidated = false;
}
[blue]return formValidated;[/blue]
}
[/tt]
You can make it less clumsy by set up a variable for document.forms[0].SimList... etc. I sure leave it and other possible details for making it more concise to you to do it.
 
The select has to be multiple for future functionality, as per the clients instruction. This helps a lot though, thank you very much.

Soul Pumpkin
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top