views:

43

answers:

3

This works but only if ALL SELECTS == 1, as soon as I change one SELECT to something else, this returns true... why?

BACKGROUND: To validate a form. I am getting all SELECT values inside a div (which contains more divs) and compare them to the number '1', and if they == 1, then an error div shows up for the user.

some code for getting all select values:

     var subcats = document.getElementById("annonsera_subcats").getElementsByTagName("select");
     subcatsValid(subcats)) etc etc...

Then I am using this loop in the function subcatsValid():

      function subcatsValid(fld){

      for (i=0; i<fld.length; i++){
 if (fld[i].value==1){
 document.getElementById("annonsera_subcatsempty_error").style.display='block';
  document.getElementById("annonsera_subcats").focus();
  return false;
  }
 document.getElementById("annonsera_subcatsempty_error").style.display='none';
 return true;
 }
            }

I think the problem is in the loop... Please help! Thanks

+4  A: 

You should move return true outside of for loop. Otherwise first SELECT with value other than 1 returns true.

Majkel
haha, missed that one
Camran
A: 
function subcatsValid(fld)
{
    document.getElementById("annonsera_subcatsempty_error").style.display='none';
    for (i=0; i<fld.length; i++)
    {
     if (fld[i].value==1)
     {
      document.getElementById("annonsera_subcatsempty_error").style.display='block';
      document.getElementById("annonsera_subcats").focus();
      return false;
     }
    }
    return true;
}

Change the location of "return true"

Salman A
A: 

The problem is that the return statement is inside the loop. This means that when one of the fields != 1 (not equal to one) then the for loop returns true and the loop and method are exited.

You can simply move the return true statement outside of the loop as follows:

function subcatsValid(fld){

      for (i=0; i<fld.length; i++){
        if (fld[i].value==1){
        document.getElementById("annonsera_subcatsempty_error").style.display='block';
                document.getElementById("annonsera_subcats").focus();
                return false;
                }
        document.getElementById("annonsera_subcatsempty_error").style.display='none';

        }
        return true;
}
Jamie Dixon