Can I intercept a form submit action and do some JavaScript function before sending it to post/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...
You can put your form validation against this event type. The following example shows how to use onsubmit. Here we are calling a validate() function before submitting a form data to the webserver. If validate() function returns true, the form will be submitted, otherwise it will not submit the data.
To invoke this function in the html document, we have to create a simple button and using the onclick event attribute (which is an event handler) along with it, we can call the function by clicking on the button.
Step 1: Firstly, we have to type the script tag between the starting and closing of <head> tag just after the title tag. And then, type the JavaScript function. Step 2: After then, we have to call the javaScript function in the Html code for displaying the information or data on the web page.
JavaScript functions can be automatically invoked without an event. JavaScript is mainly used for actions on user events like onClick(), onMouseOver() etc. But what if you need to call a JavaScript function without any user events? Answer would be to use the onLoad() of the <body> tag.
<form action="something.php" method="post" onsubmit="return myFunction()">
<input type="text" value="Some data"/>
<input ... ... ... />
<input type="submit" value="Send"/>
<script type="text/javascript">
function myFunction(){
//do something here
//if you want to submit form
return true;
//if 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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With