Skip to content Skip to sidebar Skip to footer

Prevent Browser Jump To Top Page When Submit The Form

I am trying to prevent the page jumping to top when the user submits the form. There are many people suggesting return false. However, it also prevents the form to be submitted too

Solution 1:

When you submit the form you are effectively loading a new page. Returning false in the submit handler simply tells the browser not to bubble the event and not perform the default event, which in this case is submiting the form, which is why nothing is happening when you do this.

There are several solutions to your problem. If you are redirecting your user (after the form submission) back to the form page but with errors, you can include the "fragment identifier" in the url. Have the fragment identifier point to the ID of you form and the browser will automatically go to that part of the document. Example:

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

And your url would be:

host/path?query=querystring#my-form

If you want to avoid having the page reload, try doing your validation in JS. The jQuery validation plugin is very easy to use and simply fantastic. See here to find out how to use it. It's great because it does most of the heavy lifting for you and has a set of common, default validation methods.

Alternatively you can submit your form via ajax and return any validation errors that the server picks up. If you don't have any errors then you can redirect to the next page. If there are errors then stick them in the form or display an alert. This solution will avoid you having to replicate any complex validation logic on the client (if you want to use the jQuery validate plugin).

Solution 2:

Try to use preventDefault() in jquery ..

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

Solution 3:

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

try to use 'button' form type (also with #ajax callback).

Post a Comment for "Prevent Browser Jump To Top Page When Submit The Form"