Easily Catch Enter to Submit Form
Asked Answered
I

2

8

Is there an easy way to enable hitting enter to execute some javascript for a form with paper-input's. I can catch the keystroke on enter for every element but this seems kind of tedious.

Interpretation answered 27/7, 2014 at 22:37 Comment(0)
W
8

With the current Polymer version 1.0 I was able to resolve that using iron-a11y-keys.

Here is an example bound to the whole form which triggers submission on any child input element:

<iron-a11y-keys id="a11y" target="[[_form]]" keys="enter"
                  on-keys-pressed="submitForm"></iron-a11y-keys>
  <form is="iron-form" id="form"
        method="post"
        action="{{url}}">

...

Polymer({
  is: 'example-form',
  properties: {
    _form: {
      type: Object,
      value: function() {
        return this.$.form;
      }
    }
  },
  submitForm: function() {
    document.getElementById('form').submit();
  },
Wart answered 4/1, 2016 at 9:0 Comment(0)
L
5

Currently (Polymer 0.3.4) there seems to be no event fired when one presses the enter key in a paper-input. But you can extend the paper-input element and add this functionality (see Extending other elements in the Polymer doc):

<polymer-element name="my-paper-input" extends="paper-input">
  <template>
    <shadow></shadow>
  </template>
  ...
</polymer-element>

Then you can fire a custom event when the return key is pressed:

ready: function() {
  self = this;
  this.$.input.addEventListener('keypress', function(e) {
    if (e.keyCode == 13) {
      self.async(function() {
        self.fire('enter', self.value);
      });
    }
  });
}

For convenience the input value is passed to the event handler. Now you can use your new element like so:

<my-paper-input ... on-enter="{{inputEntered}}"></my-paper-input>

Edit 1:

Since the event bubbles up in the element hierarchy, one can catch it on the surrounding form element:

<my-form on-enter="{{anyInputEntered}}" ...>

Then one gets the events of all input elements in one place (the event propagation can be stopped by calling stopPropagation(); on the event object).

Edit 2:

It's best to give custom events unique names, so that they don't clash with the names of core events that may be added in the future (e.g. my-unique-prefix-input-entered).

Lumen answered 27/7, 2014 at 23:34 Comment(2)
That is what I was trying to avoid, having to put on-enter="{{inputEntered}}" on a bunch of elements in html. I was trying to see if there was something that could just cover all elements in a form. Thanks for the suggestion though :-)Interpretation
You can catch the event anywhere above in your element hierarchy. Put the event handler on your surrounding form element for example. Then you get the events from all inputs in one place. Another way for distributing events is core-signals. These events can be received anywhere in your app (though i wouldn't recommend it for this scenario).Lumen

© 2022 - 2024 — McMap. All rights reserved.