Why doesn't the second function gets called when onclick event handling mechanism is initiated?

Consider the snippet,

<input type="button" value="Press Me!" id="my" onclick="return executeX(); executeY()">
<script>
    function executeX() {
        alert("in X");
        return true;
    }

    function executeY() {
        alert("in Y");
    }
</script>

Even though true is returned from first function, why doesn't the control forwards to executeY() within onclick?

Upvotes: 0

Views: 36

Answers (4)

you return a value(executeX()) before calling the second function(executeX()).

function example() {
    //Do Something
    return /*Return Something*/;
    //this Code will not be executed
}

possible solution:

<input type="button" value="Press Me!" id="my" onclick="function(){ executeY(); return executeX(); }">

Upvotes: 0

Barmar
Barmar

Reputation: 781290

Use && to combine them:

onclick="return executeX() && executeY();"

The short-circuiting of && ensures that executeY() will only be called if executeX() returns truth.

Upvotes: 3

AmmarCSE
AmmarCSE

Reputation: 30567

This is because you started your inline javascript with return. Therefore, as soon as the first function executed its result was returned.

Either remove the return or have the second function called at the end of the first function.

            function executeX(){
                alert("in X");
                executeY();
                return true;
            }   

            function executeY(){
                alert("in Y");
            }

Upvotes: 1

SalDev
SalDev

Reputation: 388

Because in your onclick handler you are returning with the result of the first function. It's like a function: once you return, no other lines will be performed.

Upvotes: 1

Related Questions