Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute javascript code straight before page submit

Tags:

javascript

There are a few similar questions to this but none quite the same.

I want to know if there is an event that can be used to execute some JS before a page is submitting (i.e. POSTed).

like image 605
ale Avatar asked Nov 15 '11 08:11

ale


People also ask

Can I run JavaScript before the whole page is loaded?

But yes, it is an option.

Does Onclick fire before submit?

Working example Just wondering... is it possible that the form will be submitted before the hidden field gets updated? Wouldn't it be wise to first prevent the submission, then change the hidden field, and first then submit it? When using a click() event on the button, yes it is.

How do you run JS function on form submit?

To call and run a JavaScript function from an HTML form submit event, you need to assign the function that you want to run to the onsubmit event attribute. By assigning the test() function to the onsubmit attribute, the test() function will be called every time the form is submitted.


1 Answers

Something like this?

<form onsubmit="do_something()">  function do_something(){    // Do your stuff here } 

If you put return like the code below, you can prevent the form submission by returning false from the do_something() function.

<form onsubmit="return do_something()">  function do_something(){    // Do your stuff here    return true; // submit the form     return false; // don't submit the form } 
like image 120
Moe Sweet Avatar answered Sep 20 '22 12:09

Moe Sweet