Prevent form from refreshing page

Ember noob here,

I created a form and would like to call my action on submit.

<form {{on "submit" (fn this.search this.input_value)}}>
  <Input @value={{ this.input_value }} />
  <button type="submit"> Search </button>
</form>

(in my component I have my search action)

 ....

 @action
 async search(full_name) {
  ...
 }

I can see the search action being triggered but right after the pages refreshes. do you know how I can prevent this?

I tried to use a on "click" on the button. but if i mistakenly click press the return key it will trigger the form and refresh the page :frowning:

Hey @Jacopo_Scrinzi :wave: welcome to the Ember forum :tada:

So you are currently missing one little thing to make this work the way that you want, it’s not something specific to Ember but rather a “vanilla Javascript” thing that you now need to do because Ember is using the platform more and more these days.

You will need to make sure that you prevent the default behaviour of the form from javascript. You can read more about it in the MDN article but if you google “Form refresh Javascript” then you’ll see a bunch of stack-overflow questions suggesting that you should call e.preventDefault() on the event.

What that looks like with your current code setup:

....

@action
async search(full_name, event) {
  event.preventDefault();
  ...  
}

That should work for you :+1: let me know if you have any other questions

3 Likes

Thanks @real_ate !! Just tried it and it worked :blush:

2 Likes