6

Can I intercept a form submit action and do some JavaScript function before sending it to POST or GET?

For example:

<form action="something.php" method="post">
     <input type="text" value="Some data"/>
     <input ... ... ... />
     <input type="submit" value="Send"/>

</form>

Is there a way I can call a JavaScript function before calling action when I click the submit button?

javascriptFunction();
// Now go to form action...
3

2 Answers 2

11
<form action="something.php" method="post" onsubmit="return myFunction()">
     <input type="text" value="Some data"/>
     <input ... ... ... />
     <input type="submit" value="Send"/>
</form>

<script type="text/javascript">
    function myFunction() {

        // Do something here

        // If you want to submit form
        return true;

        // If you don't want to submit
        return false;
    }
</script>
Sign up to request clarification or add additional context in comments.

Comments

3

Try to add an onclick event to the button

onclick="yourfunction()"

and submit the form at the end of the function

document.getElementById("yourform").submit()

1 Comment

Looks a cool workaround for calling a form from external buttons! Thanks :)

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.