GD_Java
GD_Java

Reputation: 1429

Calling two javascript function on a single click

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.

Upvotes: 1

Views: 3293

Answers (5)

Popnoodles
Popnoodles

Reputation: 28419

<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 comparison"

<a href="#" onClick="return if (firstFunction()===true) secondFunction();"> Click me </a>

but you probably don't

Upvotes: 1

Willem D&#39;Haeseleer
Willem D&#39;Haeseleer

Reputation: 20200

You can do that like this

<a href="#" onClick="return firstFunction() ? secondFunction() : false"> Click me </a>

Upvotes: 3

gdoron
gdoron

Reputation: 150313

<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.
}

Upvotes: 1

Josh Anderson
Josh Anderson

Reputation: 6005

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>

Upvotes: 3

Quentin
Quentin

Reputation: 944545

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();
    }
}

Upvotes: 2

Related Questions