Home > front end >  onchange Submit Form with Page Anchor
onchange Submit Form with Page Anchor

Time:07-04

Using something like this code is there anyway of passing a html anchor to jump to a particular place in the page when it has been submitted?

onChange="document.form2.submit()"

Im using this code above for a dropdown menu which submits after selection, but i also need it to pass a page anchor.. is this doable?

many thanks

ps The anchor will depend on which dropdown menu was used. There are, for example, around 40 dropdown menus in a page.. so when you get over 20 you have to keep scrolling down to select the next one.. this is why i need the page, after submitting, to jump to the last dropdown used... Hope this makes sense.

CodePudding user response:

Set the action of the form to url#your-hash right before you submit.

function change_url(form, hash) {
  form.setAttribute("action", "https://example.com/#"   hash);
  form.submit();
}

document.querySelectorAll("select").forEach(function(elem) {
  elem.addEventListener("change", function() {
    var hash = this.getAttribute("name");
    var form = this.closest("form")
    change_url(form, hash);
  })
})
<h1>fill the form</h1>
<form action="" method="get" onsubmit="change_url(this); return false">


  <a name="sel1"></a>
  <select name="sel1">
    <option></option>
    <option>sel1</option>
  </select>

  <div style="height:500px"></div>

  <a name="sel2"></a>
  <select name="sel2">
    <option></option>
    <option>sel2</option>
  </select>

  <div style="height:500px"></div>

  <a name="sel3"></a>
  <select name="sel3">
    <option></option>
    <option>sel3</option>
  </select>

  <div style="height:500px"></div>

  <button>submit</button>
</form>

  • Related