I have a JSP page containing an href link. When the link is clicked, I need to call 2 javascript functions. The second javascript function should execute only if first function returns true
. I have tried this:
<a href="#" onClick="return firstFunction(); secondFunction()"> Click me </a>
But this is not working. All I want is that a second function gets executed if the first function returns true.
I have a JSP page containing an href link. When the link is clicked, I need to call 2 javascript functions. The second javascript function should execute only if first function returns true
. I have tried this:
<a href="#" onClick="return firstFunction(); secondFunction()"> Click me </a>
But this is not working. All I want is that a second function gets executed if the first function returns true.
Share Improve this question edited Jan 5, 2013 at 20:56 Leigh 28.9k10 gold badges57 silver badges109 bronze badges asked Jan 5, 2013 at 20:30 GD_JavaGD_Java 1,4516 gold badges26 silver badges42 bronze badges5 Answers
Reset to default 3You can do that like this
<a href="#" onClick="return firstFunction() ? secondFunction() : false"> Click me </a>
When you return the result of your first function the block is exited. Unless you're going to do something with the result, you should say:
<a href="#" onClick="return firstFunction() ? secondFunction() : false;">Click me</a>
You currently have:
function () {
return firstFunction();
secondFunction();
}
This calls firstFunction
then returns its value, and never reaches the call to secondFunction
.
You want:
function () {
var result = firstFunction();
if (result) {
secondFunction();
}
}
<a href="#" onClick="foo()"> Click me </a>
function foo(){
if (firstFunction() === true)
secondFunction()
}
return
exit the function so you just returned firstFunction
and exited the function, like
function foo(){
return firstFunction();
secondFunction(); // Unreachable code.
}
<a href="#" onClick="return if (firstFunction()) secondFunction();"> Click me </a>
if you want true to mean "only true and not just something that = true using a boolean parison"
<a href="#" onClick="return if (firstFunction()===true) secondFunction();"> Click me </a>
but you probably don't