简体   繁体   中英

Jump to anchor on submit

I want to jump down to an anchor tag once a form is submitted. Is this possible?

my simplified form looks like this

  <form onsubmit="searchFunc()">
    <input type="text" value="Search"  />
</form>

and I want it to jump to an anchor or a div (ideal)

<a name="myAnchor"></a>

<div id="myAnchor"></div>

Return the HTML response, either redirecting to the URL with a #myAnchor on the end; or with a bit of Javascript embedded in the page, that will scroll/ focus to the desired part.

response.sendRedirect("customerEdit#myAnchor");

Or in JS:

$(document).ready( function(){
  var scrollToElement = $("#someElement");
  $(window).scrollTop( scrollToElement.offset().top);
});

HTML form POST is, of course, a round-trip to the server. So you can't scroll on the old page, you have to scroll or go (by redirect) to the anchor on the new page.

If you're using AJAX to post, you will of course stay on the existing page & can do whatever you wish. But that's a different kettle of fish.

Is the form submitting to the server and reloading the page?

If not, and you're using jQuery, stick this in after you've processed the form:

 $('html, body').animate({
     scrollTop: $("#myAnchor").offset().top
 });

Alternatively you could use the same script after loading the results page, or use jQuery AJAX to submit the form using $.ajax or $.post and $("form").serialize .

You could just make an array of DOM anchor elements and grab the first item out of that array, also being the first anchor tag on the page.

<script type="text/javascript">
function get_anchor(){
   var anchors = document.getElementsByTagName("a");
   var first_anchor = anchors[0];
   // Do something with the anchor we've now stored as a variable
   return first_anchor.text;
}
</script>




<form onsubmit="get_anchor()">
    <input type="text" name="somename">
    <input type="submit">
</form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM