Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I catch that enter is pressed in Polymer 1.0 paper-input

Tags:

polymer

How do I catch when enter is pressed in Polymer 1.0 paper-input?

I tried with the on-bind-value-changed that is exposed through the iron-input, but it seems it only differentiates with letters in the event argument where e.detail is null on all other keys, such as enter, tab, etc.

like image 283
Franz Thomsen Avatar asked Jul 06 '15 12:07

Franz Thomsen


2 Answers

I would bind a keydown event to the input that called a function. In there you can find which key was pressed. For example:

<dom-module id="test-element">
    <template>
        <!-- add keydown listener to paper input -->
        <paper-input label="Input label" on-keydown="checkForEnter"></paper-input>
    </template>
    <script>
        Polymer({
            is: "test-element",
            checkForEnter: function (e) {
                // check if 'enter' was pressed
                if (e.keyCode === 13) {
                    // enter pressed!
                }
            }
        });
    </script>
</dom-module>
like image 163
Ben Thomas Avatar answered Nov 16 '22 05:11

Ben Thomas


Another possibility would be to use iron-a11y-keys. That way, you could declaratively define what's happening when the user presses the enter key while the focus is on the paper-input element.

Example (copied from the Polymer Catalog):

<iron-a11y-keys id="a11y" target="[[target]]" keys="enter"
                on-keys-pressed="onEnter"></iron-a11y-keys>
<paper-input id="input" placeholder="Type something. Press enter. Check console." value="{{userInput::input}}"></paper-input>

After that, you will have to bind the target property of the a11y element to the paper-input element, like so:

...
properties: {
  userInput: {
    type: String,
    notify: true,
  },
  target: {
    type: Object,
    value: function() {
      return this.$.input;
    }
  },
},
onEnter: function() {
  console.log(this.userInput);
}
...

Hope that helps. See iron-a11y-keys for more information.

like image 43
Christof Avatar answered Nov 16 '22 07:11

Christof