Fuczi Fuczi
Fuczi Fuczi

Reputation: 415

Call a JavaScript function before an action in an HTML form

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

Upvotes: 6

Views: 10340

Answers (2)

geekbro
geekbro

Reputation: 1323

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

Upvotes: 11

Kjub
Kjub

Reputation: 92

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

Upvotes: 3

Related Questions