Prevent browser from going to the top page when submitting a form

I am trying to prevent page overflow when a user submits a form. There are many people offering return false . However, it also prohibits form submission.

I was wondering if anyone could help me with this.

 **JQuery** $('#submit').click(function(){ //doesn't work return false; }) $('form').submit(function(){ //doesn't work either return false; }) **Html** <form...> <input>... <input>... <input>... <input type='submit' id='submit' value='submit'> </form> 
+4
source share
3 answers

When you submit the form, you load a new page. Returning false in the submit handler simply tells the browser not to bubble the event and not to execute the default event, which in this case sends the form, so nothing happens when you do this.

There are several solutions to your problem. If you redirect your user (after submitting the form) back to the form page, but with errors, you can include the "fragment identifier" in the URL. The fragment identifier indicates the identifier of your form, and the browser will automatically go to that part of the document. Example:

 <form id="my-form"> ... </form> 

And your url will be:

 host/path?query=querystring#my-form 

If you want to avoid reloading the page, try checking in JS. The jQuery validation plugin is very easy to use and just fantastic. See here for how to use it. This is great because it does most of the hard work for you and has a set of common validation methods by default.

Alternatively, you can submit the form via ajax and return any validation errors that the server picks up. If you have no errors, you can redirect to the next page. If there are errors, insert them into the form or show a warning. This solution will allow you not to replicate any complex validation logic on the client (if you want to use the jQuery validation plugin).

+2
source

Try using preventDefault () in jquery ..

 $('#submit').click(function(e){ e.preventDefault(); }); 
+3
source

In the case of using the submit form type (with the #ajax callback) in jQuery dialogs on drupal forms:

try using the button form type (also with the #ajax callback).

0
source

Source: https://habr.com/ru/post/1400328/


All Articles