Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form Submit Execute JavaScript Best Practice? [closed]

I would like to run a JavaScript function when a form is submitted. The issue is that, when the form is submitted, the page is reloaded and the form values are appended to the URL as GET parameters. I would like it to stay on the current page and only run the JavaScript function.

I was wondering what the best practice (or what you do) to avoid having the page reload and parameters be sent.

like image 799
gberg927 Avatar asked Nov 10 '11 16:11

gberg927


People also ask

What is correct way to submit a form using JavaScript?

In javascript onclick event , you can use form. submit() method to submit form. You can perform submit action by, submit button, by clicking on hyperlink, button and image tag etc. You can also perform javascript form submission by form attributes like id, name, class, tag name as well.

How do I keep form data after submitting the form using JavaScript?

To keep the values, you must fill in the values on the server while rendering the page. Usually, you can simply copy the data from the HTML request parameters into the fields. Usually, you cannot simply copy the HTML request parameters into the fields.

How do you close a form in JavaScript?

close() method simply close the window or tab opened by the window. open() method. Remember that - You have to define a global JavaScript variable to hold the value returned by window. open() method, which will be used later by the close() method to close that opened window.

How do I close a form after submitting?

In the Form Settings->On Submit->Redirect URL set this value : javascript:window. top. close();


1 Answers

Use the onsubmit event to execute JavaScript code when the form is submitted. You can then return false or call the passed event's preventDefault method to disable the form submission.

For example:

<script> function doSomething() {     alert('Form submitted!');     return false; } </script>  <form onsubmit="return doSomething();" class="my-form">     <input type="submit" value="Submit"> </form> 

This works, but it's best not to litter your HTML with JavaScript, just as you shouldn't write lots of inline CSS rules. Many Javascript frameworks facilitate this separation of concerns. In jQuery you bind an event using JavaScript code like so:

<script> $('.my-form').on('submit', function () {     alert('Form submitted!');     return false; }); </script>  <form class="my-form">     <input type="submit" value="Submit"> </form> 
like image 60
moteutsch Avatar answered Sep 22 '22 02:09

moteutsch