user2449684
user2449684

Reputation: 1

How to call javascript function inside another function onsubmit form?

function toggle1() {
    //code toogle1

    function toggle2() {
        //code toogle2
    }
}

I want to call toggle2() in the onsubmit of the form:

<form name="myForm" action="blabla.php" onsubmit="return toogle2()" method="post">

I have no clue about this, thanks in advance.

Upvotes: 0

Views: 549

Answers (2)

5z- -
5z- -

Reputation: 161

function toggle1() {
    //code toogle1
    toggle2();
}

function toggle2() {
   //code toogle2
}

If I was you,I would like use the above way

Upvotes: 1

Quentin
Quentin

Reputation: 943185

toggle2 is defined within the scope of toggle1, so it isn't a global and is not accessible.

You could assign it to a global:

function toggle1() {
    //code toogle1

    function toggle2() {
        //code toogle2
    }

    window.toggle2 = toggle2;

}

… but it wouldn't be available until toggle1 was called.

Globals are generally a bad idea though. In most cases you are usually better off not using them. This makes the onXXX attributes unusable so you would have to switch to something more modern (addEventListener, either directly or through an abstraction library).

function toggle1() {
    //code toogle1

    function toggle2() {
        //code toogle2
    }

    document.querySelector('form').addEventListener('submit', toggle2);

}

You'd still need to call toggle1 before it could be used though.

Upvotes: 1

Related Questions