views:

540

answers:

4

I am performing two validations on the client side on the samve event. I have defined my validations as shown below

btnSearch.Attributes["OnClick"] = "javascript:return prepareSave(); return prepareSearch();"

Pseudo code for

prepareSave():
{
  if (bPendingchanges)
    {
     return confirm('Need to save pending changes first, click OK and loose changes or cancel to save them first')
    }
  else
   {return true}
}

Pseudo code for

prepareSearch():
{
  if (bNoSearchText)
    {
      alert('Please specify search criteria before proceeding')
      return false;
   }
  else
   {return true;}
}

When bPendingchanges=false, I never get the second validation running. Anyone who can quickly spot what I have overlooked here? Please?

A: 

Your second return statement will never be reached. Execution stops after javascript:return prepareSave().

Looks like you want to return true if both functions return true - therefore, do:

btnSearch.Attributes["OnClick"] = javascript: return prepareSave() && prepareSearch();
matt b
That code will execute the validations only once, when the button is setup. You want to wrap then in an anonymous function or make them a string.
sblundy
Why is an answer identical to three other answers the only one voted down?
matt b
Also I'm not looking to correct the way he is attaching the handler to the object (which could be improved), just the unreachable return statement.
matt b
Easy guys, thanks. I can now invoke both validations. Good stuff.
J Angwenyi
A: 

That's because the return prevents the second validation from running. Try this

btnSearch.Attributes["OnClick"] = "javascript:return prepareSave() && prepareSearch();"
sblundy
A: 

"javascript:return prepareSave(); return prepareSearch();"

1) You shouldn't have the "javascript:"
2) return prepareSearch(); will never be executed, because "return prepareSave(); exits your event handler

Try "return (prepareSave() && prepareSearch());"

Greg
+2  A: 

return, as the name implies, returns control back to whatever called the code in question. Therefore, anything that's after a return statement

return prepareSave(); return prepareSearch();
//                    ^^^^^^^^^^^^^^^^^^^^^^^ e.g. this part

never executes. Try return (prepareSave() && prepareSearch());

Piskvor