[SalesForce] Enter key capture for lightning input tag

How can I capture the enter key press action in the js controller for lightning:input text. below is the code in the component file.

 <div class="slds-form-element">
       <lightning:input aura:id="firstNameId" label="First Name" 
                 value="{!v.firstName}" placeholder="First Name"/>
 </div>
  <div class="slds-form-element"  >
      <lightning:button variant="brand" label="Search" 
                 onclick="{! c.buttonAction }" />

  </div>

Best Answer

The lightning:input component has an onchange attribute:

The action triggered when a value attribute changes.

component.cmp

<lightning:input label="Name" name="myname" onchange="{! c.changeHandler }"/>

controller.js

changeHandler : function(component, event, helper) {
    validate that enterKey was pressed and do some action

}

the documentation for the component can be found here

you can use keycode.info for checking character codes, as to actually identifying the key value in your function, you can refer to Working with Events in Javascript

UPDATE: for some reason, unable to fetch Key event parameters when using lightning input.

Workaround is to wrap the component in an HTML tag that supports onkeypress events:

All HTML elements, EXCEPT:

<base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style>, and <title>

and a us the event.which property to listen for the pressed key

<div onkeypress="{!c.controllerMethod}">
    <lightning:input --attributes-- />
</div>

Tested and works (Winter '18)