Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a javascript function before action in html Form

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...
like image 985
Fuczi Fuczi Avatar asked Nov 21 '16 00:11

Fuczi Fuczi


People also ask

How do you call a function before submitting a form?

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.

How do you call a function in HTML form?

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.

How do you call a JavaScript function from HTML?

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.

How can call JavaScript function without any event in HTML?

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.


2 Answers

    <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>
like image 171
geekbro Avatar answered Sep 21 '22 00:09

geekbro


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()
like image 25
Kjub Avatar answered Sep 23 '22 00:09

Kjub