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

8
  • 1
    Why would you want this? Why not just call toggle1()? Commented Jun 9, 2013 at 8:45
  • @Anickyan because there are some things that make i want call toogle2() inside toogle1() , is there a way to call toogle2 ? thanks Commented Jun 9, 2013 at 8:48
  • you need to return toggle2 in toggle1 to access it out of the toggle1 scope Commented Jun 9, 2013 at 8:49
  • Just take toggle2() outside of toggle1() to make it global. Case solved. Commented Jun 9, 2013 at 8:50
  • @user2449684 If you want to call toggle2 from inside toggle1 you could just move it outside, it would still be callable by toggle1. The only reason I see for doing this would be to hide toggle2 from any code outside toggle1. Commented Jun 9, 2013 at 8:54

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks @Quentin for the answer , it worked , but you right still need to call toggle1 first , really bad method what i do , i will move toogle2() to outside
1
function toggle1() {
    //code toogle1
    toggle2();
}

function toggle2() {
   //code toogle2
}

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.