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...
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...
Share
Improve this question
edited Jul 20, 2023 at 18:18
Peter Mortensen
31.6k22 gold badges110 silver badges133 bronze badges
asked Nov 21, 2016 at 0:25
Fuczi FucziFuczi Fuczi
4152 gold badges5 silver badges13 bronze badges
3
- 3 The onSubmit event is what you're looking for. – Steve G Commented Nov 21, 2016 at 0:27
- Possible duplicate of stackoverflow./q/5897360/2182349 – user2182349 Commented Nov 21, 2016 at 0:33
- 3 Possible duplicate of before form submit call function javascript – K Scandrett Commented Nov 21, 2016 at 0:56
2 Answers
Reset to default 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>
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()