3

I want to read in my javascript controller what key is pressed in my lightning component. This is the lightning:input that I want to read.

    <lightning:input value="{!v.username}" aura:id="username" name="username" 
 onchange="{!c.onKeyUp}" class="input border sfdc_usernameinput sfdc lightFont loginWidth" label="{!$Label.c.B2B_Your_Email}" />

What do I have to do on the onchange to be able to read it out.

2 Answers 2

5

This can be done using an eventlistener on the keydown-event and reading the keycode. To use it on your input only, you need to register the eventlistener on that input field rather than the window-object (which is used in the example).

window.addEventListener("keydown", function(event) {
  alert("key: " + event.key + ", code: " + event.code);
}, true);

Related documentation:

2

In the context of a lightning component, you can access the event object and it's properties in both your controller and helper.

<ui:inputText value="{!v.val}"  keyup="{!c.onKeyUp}" />

Controller.js

({
    onKeyUp: function(component, event, helper)
    {
        helper.doKeyUp(component, event);
    }
})

Helper.js

({
    doKeyUp: function(component, event)
    {
        // access the event object in the helper using getParam() or getParams()
        console.log(event.getParam('keyCode'));
        console.log(event.getParams().keyCode);
    }
})

You should be able to access any properties available on the standard Javascript Event object using this method, more information about the Event object can be found here: https://developer.mozilla.org/en/docs/Web/API/Event

I would also recommended taking a look at the Javascript API documentation found in the Aura Reference App which you can find by navigating to the following URL:

https://yourdomain.lightning.force.com/auradocs/reference.app#reference?topic=api:Event

1
  • Just to add on in the answer if someone still struggling, please use event.keyCode,
    – Navii
    Apr 28, 2020 at 6:11

Not the answer you're looking for? Browse other questions tagged or ask your own question.