Lightning

KeyCode of a key pressed in Lightning Web Component

There will be a scenario where you need to identify if Enter is presses or any special character is pressed. Below code will demonstrate how to identify a keypress code. In Lightning Web Component.

For this scenario we need to add a span section with onkeypress event above the input text field. And call a JS method. Something like this.


lwc_Key_Code_Checker.html

<template>
    <span onkeypress={key_Code_Checker}>
        <lightning-input id="a_Name_Id" 
                         label="Enter Name: " 
                         type="text" 
                         onchange={on_Change_Event}>
        </lightning-input>
    </span>
</template>

lwc_Key_Code_Checker.js

import { LightningElement, track } from 'lwc';

export default class Lwc_Key_Code_Check extends LightningElement {

    @track a_Text_Value;

    key_Code_Checker(component, event, helper){
        if (component.which == 13){
            // JS code follows.
            var a_Name = this.a_Text_Value;
            alert('Entered name is: '+a_Name);
        }
    }

    on_Change_Event(event){
        var a_Name = event.target.value;
        this.a_Text_Value = a_Name;
    }
}

lwc_Key_Code_Checker.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>48.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
        <target>lightning__AppPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

Output:

One thought on “KeyCode of a key pressed in Lightning Web Component

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s