Enter key pressed inside a lightning input

I have a lightning:input and when the focus is on it and you type the enter stroke: it refreshes the page.

I tried to prevent it by implementing the onchange: avoid the event to be fire but the callback is never launched.

Component.cmp:

<lightning:input
  type="email"
  onchange="{! c.callbackNeverCalled }"
/>

Controller.js:

callbackNeverCalled: function(component, event, helper) {
  event.preventDefault(); // Does not prevent from refreshing/redirecting the page & also 'deprecated'.

  event.getSource().getParams(); 
  // Is an empty object but the good way to do (cf. documentation)
}

Answer

Thanks to SFDCFOX and PatMcClellan__c.
Workaround is:

<span onkeypress="{!c.keyCheck}" class="slds-size--11-of-12">
    <lightning:input aura:id="body" label="" name="Body" placeholder="Enter message..." value="{!v.Message.Body__c}" />
</span>

keyCheck : function(component, event, helper){
    if (event.which == 13){
        helper.onSend(component, event);
    }    
}

Attribution
Source : Link , Question Author : Simonp , Answer Author : Karel L

Leave a Comment