Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inputs on Ember refresh page when a user hits Enter key

Tags:

ember.js

I'm using Ember CLI and have noticed odd behaviour. When the user clicks into the input and presses the enter key, the page refreshes.

My page has a basic element like this that is NOT part of any form:

<input type="text" class="form-control" id="per_page" value="50">

I am currently serving the page via:

ember cli

So node is hosting and has the fancy live reload thing going on so that when I update a page that is part of the underlying app.

So what is causing a page reload the enter key pressed inside an input? Could it be node or live reload? Are inputs just supposed to refresh a page when a user presses the enter key and I missed that in my HTML for dummies book?

**Better still, how can I intercept and instead call a function via:

{{action** "myFunction"}}
like image 712
Jim Avatar asked Dec 25 '22 04:12

Jim


2 Answers

That happens because when you hit Enter, form gets submitted which results in page reload. what you need to do is set onsubmit="return false" on the form so nothing happens during submit. you can bind input to execute some action by adding action attribute action="doSomething"

<form onsubmit="return false">
        {{input type="text" action="createComment" value=topic id="inputTopic"}}
</form>
like image 100
Iuri G. Avatar answered Dec 29 '22 15:12

Iuri G.


Edit: In Ember 3+ you now use the {{on}} modifier to setup events on elements.

<form {{on 'submit' this.submitForm}}>
  <!-- the rest of your form here -->

  <button type='submit'>Submit</button>
</form>

And the action defined like so

@action
submitForm(event) {
  event.preventDefault();
  // Your code
}

Historically Ember has handled this use case with the following code:

<form {{action 'submitForm' on='submit'}}>
  <!-- the rest of your form here -->

  <button type='submit'>Submit</button>
</form>

This prevents the form from refreshing the page.

There is another method that gives you more control, by giving you the event so you can manage that yourself:

<form onsubmit={{action 'submitForm'}}>
  <!-- the rest of your form here -->

  <button type='submit'>Submit</button>
</form>

In this case, you will get an event and will have to call event.preventDefault() to stop the page refresh.

actions: {
  submitForm(event) {
    event.preventDefault();
  }
}

This is a running example of the two: https://ember-twiddle.com/827820958e054f7af57b7677630729fc?openFiles=controllers.application.js%2C

like image 25
knownasilya Avatar answered Dec 29 '22 15:12

knownasilya