1

I have an HTML form that I am trying to use to navigate to a different page. I was trying to use window.location.replace to append the value of the input to the end of the form like this:

Before: https://example.com/search

After: https://example.com/search/formvalue

I have tried just about every trick I can find, but have had no luck. I was able to get it working by replacing window.location.replace with window.open, but I don't want to have to open it in a new tab. I also tried window.location.assign but had no more luck with that. I tried running both of these functions in the Chrome console and they worked fine from there. My code is below.

function onenter() {
  var term = document.getElementById("searchbox").value;
  window.location.replace("/search/" + term);
}
<form method="GET" onsubmit="onenter();">
  <input id="searchbox" name="term" type="text" autofocus>
  <button id="searchenter" type="submit">Enter</button>
</form>

What am I doing wrong/missing?

Community
  • 1
  • 1
kevinuulong
  • 530
  • 1
  • 4
  • 17
  • This may help you if you are trying to do something similar. [How to modify the URL without reloading the page](https://stackoverflow.com/questions/824349/how-to-modify-the-url-without-reloading-the-page) – k3llydev Mar 14 '19 at 01:54

1 Answers1

3

Your issue is that the form submission reloads the page. Use eventObject.preventDefault:

function onenter(event) {
  event.preventDefault();
  var term = document.getElementById("searchbox").value;
  window.location.replace("/search/" + term);
  console.log(window.location);
}
<form method="GET" onsubmit="onenter(e);">
  <input id="searchbox" name="term" type="text" autofocus>
  <button id="searchenter" type="submit">Enter</button>
</form>
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79