[thelist] Javascript Form Validation Question

.jeff jeff at members.evolt.org
Wed Feb 27 00:36:01 CST 2002


bm,

><><><><><><><><><><><><><><><><><><><><><><><><><><><><><
> From: bread_man
>
> Anyone have any luck validating a drop-down menu in
> Netscape? I've been struggling with this for a bit now
> and would really appreciate some help.
><><><><><><><><><><><><><><><><><><><><><><><><><><><><><

yup.  once you understand that a select is an array of options and their
values you're set.  there are two properties that will help you --
selectedIndex of the select and selected of the individual options.

if you're trying to validate a select-one, then you're new best friend is
selectedIndex:

if(myForm.mySelect.selectedIndex == -1)
{
  // nothing is selected
}

or, use it to access the selected option's value, in case you have some
blank ones you don't want them selecting:

if(myForm.mySelect.selectedIndex != -1 &&
myForm.mySelect.options[myForm.mySelect.selectedIndex].value == '')
{
  // an option with a value of '' is selected.
}

if you're trying to validate a select-multiple, then you'll need to do a bit
more work.  you gotta loop through each of the options to see if any of them
are selected.  if you only care that at least one is selected you can break
out of the loop once you find the first one.

var hasSelections = false;
for(var i = 0; i < myForm.mySelect.options.length; i++)
{
  if(myForm.mySelect.options[i].selected)
  {
    hasSelections = true;
    break;
  }
}
if(!hasSelections)
{
  // nothing is selected
}

if you need at least a certain number, you'll need to keep track of that
instead and not break out of the loop:

var hasSelections = 0;
for(var i = 0; i < myForm.mySelect.options.length; i++)
{
  if(myForm.mySelect.options[i].selected)
  {
    hasSelections++;
  }
}
if(hasSelections < 3)
{
  // not enough are selected
}

holler if you need more.

good luck,

.jeff

http://evolt.org/
jeff at members.evolt.org
http://members.evolt.org/jeff/




More information about the thelist mailing list