kinn
kinn

Reputation: 63

Calling two functions in the OnClientClick event

I want to check two conditions in the OnClientClick event of an asp.net button control. I tried this but it is only checking the first function.

OnClientClick="javascript:shouldSubmit=true; return checkFunction1(); return checkFunction2();

What is the correct way do it?

Upvotes: 2

Views: 22144

Answers (3)

Zhaph - Ben Duguid
Zhaph - Ben Duguid

Reputation: 26956

Without knowing any more about the two functions, I'd suggest something along the following lines:

... OnClientClick="return check();" ...

function check(){
  // Call function1 and save the return value.
  var success1 = checkFunction1();
  // Call function2 and save the return value.
  var success2 = checkFunction2();

  // Return the logical combination of the two values:
  // If both are true, return true, otherwise return false.
  return success1 && success2;
}

Depending on the checks you are doing, you might want to be a bit more clever about it - so if checkFunction1 returns false, then don't bother even running checkFunction2:

function check(){
  if (checkFunction1()){
    // function1 returned true, continuing:
    if (checkFunction2()){
      // function2 returned true, allow click to continue:
      return true;
    }
  }

  // One or more returned false:
  return false; 
}

If you really want to inline it all, you could do:

OnClientClick="javascript:shouldSubmit=true; return checkFunction1() && checkFunction2();

Upvotes: 3

jerjer
jerjer

Reputation: 8760

I should do it like this:

... OnClientClick="return check();" ...

function check(){
   checkFunction1();
   checkFunction2();
}

Upvotes: 0

Arief
Arief

Reputation: 6085

When you return, javascript stops executing the next statement, so you better put the "checkFunction2()" inside "checkFunction1()"

Upvotes: 0

Related Questions