0

Situation: A user submits a form. After submitting the input are tested. If the input is lacking something, I want a 'back' button that scrolls or jumps to part that is not correctly filled. Going back with javascript is trivial, but then to scroll/jump to the anchor ...

I tried

 <BUTTON onClick='window.history.go(-1);location.hash = \"#anchor\" ;'>

The page should not reload to not change the user input that is already entered.

The problem is that I first have to use window.history.back to go back to the page before submitting the form. But I have to do process the user input on the form to know what is missing. Then, after processing, I know exactly where to go, but it is the page before. I cannot use a href=gotopage.php#anchor because this reloads the page and deletes all the info the user entered in the form. history.back preserves the user input but start at the bottom of the page (firefox). I don't want - if possible - use javascript to test the user input.

ea0723
  • 805
  • 11
  • 25
user30424
  • 147
  • 1
  • 10
  • You cannot execute a script in the future... As soon as you execute `window.history.go(-1)` your current script context is gone. If you're doing client-side validation here, you'd do it *before* you submit the form and then prevent submission if there are errors. – André Dion Jun 02 '16 at 17:40
  • So there is no way to say, go back but adjust the scroll. – user30424 Jun 02 '16 at 19:46
  • moved comment to an answer to preserve formatting – ea0723 Jul 17 '16 at 05:50

3 Answers3

0

You should store the id of the element that you want to scroll to (with url parameters, cookie or with localStorage), then use the method you like from a previous answer:

How can I scroll to a specific location on the page using jquery?

I would suggest this way:

  1. When the back button is pressed, save the id of the element in localStorage
localStorage.setItem('scrollTo', '#anchor');
  1. When the page loads, check for the scrollTo in the localStorage and scroll if needed
if(localStorage.scrollTo != undefined) {
    window.location.hash = localStorage.scrollTo;
    localStorage.removeItem('scrollTo');
}
Community
  • 1
  • 1
Andras Szell
  • 527
  • 2
  • 13
0

If each section of your form has an id, you could use an anchor tag such as this:

<a href="#<INCOMPLETE ID>"> Back </a>
SulZ
  • 69
  • 5
  • before scrolling to the anchor or id I have to go back one page. After submitting the page, there is another page. – user30424 Jun 02 '16 at 17:33
0

To reset where the page lands when you jump back to the previous page, you can use

scrollTop: $(this).offset().top

after 'top', enter the offset you want (it automatically converts number to px). for instance:

scrollTop: $(this).offset().top - 260
ea0723
  • 805
  • 11
  • 25