Human Cyborg Relations
Human Cyborg Relations

Reputation: 1244

Page will refresh instead of redirecting

I have an HTML file that looks like the following:

<form onSubmit="getSearchResults()">
  <input id="search-query" type="text" placeholder="Search">
  <button onclick="getSearchResults()"></button>
</form>

<script type=text/javascript>
  var searchURL = "{% url 'search' %}" // I'm using Django, and this gets me the correct URL

  function getSearchResults(){
    var searchQuery = document.getElementById('search-query').value;
    if (searchQuery.length > 0)
        self.location.href = searchURL + '?' + searchQuery;
    else
        self.location.href = searchURL;
    return false;
  }

</script>

The idea is that every time I submit the form or click on the button, I want the page to be redirected to a different URL.

Right now, on either form submit or button click, the page just reloads. I looked at my console in Firefox and it says:

Navigated to http://localhost:8000/search
Navigated to http://localhost:8000/

So I know that my URL is correct and my code works somewhat because I am being navigated to the correct place, but then I'm being navigated to the original page I was on.

I have also tried:

window.location.href
location.href

Upvotes: 2

Views: 54

Answers (3)

Igor
Igor

Reputation: 15893

Page submits due to default type of the button.

<button type="button" ...

or

<button onclick="return getSearchResults()"></button>

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 371168

Since the button is in a form, it submits the form. Try adding e.preventDefault() inside the handler:

function getSearchResults(e) {
  e.preventDefault();
  var searchQuery = document.getElementById('search-query').value;
  if (searchQuery.length > 0)
    self.location.href = searchURL + '?' + searchQuery;
  else
    self.location.href = searchURL;
  return false;
}

Upvotes: 2

Oliver Ni
Oliver Ni

Reputation: 2662

<form onsubmit="return getSearchResults()">

Note return. This tells the onsubmit function to return what getSearchResults() returns. Otherwise return false; doesn't do anything.

Other approaches like e.preventDefault() work too.

Upvotes: 2

Related Questions