itaied
itaied

Reputation: 7107

How to submit a HTML form without redirecting?

I am writing a client-side rendering web application using react and react-router for routing. I have implemented a search with an input inside a form with react-bootstrap.

executeSearch(){
    ...
    window.location.href = '/#/search/' + formattedURL
}

let formSettings = {
  onSubmit:this.executeSearch.bind(this),
  id:"xnavbar-form"
}

const searchButton =
<Button
  onClick={this.executeSearch.bind(this)}>
  <Glyphicon glyph="search" />
</Button>

const searchInput =
<form>
  <Input
    type="text"
    ref="searchInput"
    buttonAfter={searchButton}
    placeholder="search"/>
</form>

... Jumping to the render function

<Navbar.Form
    {...formSettings}>
    {searchInput}
</Navbar.Form>

Executing a search in Mozilla Firefox works as expected: Hitting the enter key and clicking on the searchButton route me to a client-side rendered page .../#/search/....

Executing the search in Google Chrome behave like this: Clicking the searchButton works like above (client side render), but hitting the enter key cause a server redirect .../?#/search....

I figured out it is caused by the form's submit attribute, how can I modify it to render on the client?

I was thinking about listening to a keyboard ascii code (enter) for executing the search, but it seems a bit messy.

Upvotes: 0

Views: 7185

Answers (1)

Henrik Andersson
Henrik Andersson

Reputation: 47212

Stop the default behaviour of a form submit by using event.preventDefault().

This will prevent the browser from submitting your form and instead leave the "routing" logic to you to do what you want it to.

Just accept the event in your executeSearch function.

executeSearch(event){
    ...
    event.preventDefault();
    window.location.href = '/#/search/' + formattedURL;
}

Upvotes: 5

Related Questions