---
title: "Generic onChange event handler in LWC"
url: "https://blog.beyondthecloud.dev/tips/generic-onchange-event-handler-in-lwc"
category: "LWC"
published: "2024-06-07"
---

# Generic onChange event handler in LWC

Some components have many input components or elements that we need to track in our variables. Creating handler methods for onChange events is the right way to update the variable in our…

### Generic onChange event handler in LWC

Some components have many input components or elements that we need to track in our variables. Creating handler methods for onChange events is the right way to update the variable in our component.

But how can we avoid having multiple handler methods that change only the variable value?

For that, we can use a dynamic generic handler method.

Let’s check an example

```markup
<template>
    <lightning-input type='text' onchange={handleOnChangeFirstName}>
    </lightning-input>
    <lightning-input type='text' onchange={handleOnChangeLastName}>
    </lightning-input>
    <lightning-input type='checkbox' onchange={handleOnChangeIsCompany}>
    </lightning-input>
    <!-- More input components -->
</template>
```

```javascript
handleOnChangeFirstName(event) {
    this.firstName = event.target.value;
}

handleOnChangeLastName(event) {
    this.lastName = event.target.value;
}

handleOnChangeIsCompany(event) {
    this.isCompany = event.target.checked;
}

// More handlers
```

Instead, use the data custom attribute with the same name as your component variable.

```markup
<template>
    <lightning-input data-id="firstName" type='text' onchange={handleOnChangeGeneric}>
    </lightning-input>
    <lightning-input data-id="lastName" type='text' onchange={handleOnChangeGeneric}>
    </lightning-input>
    <lightning-input data-id="isCompany" type='checkbox' onchange={handleOnChangeGeneric}>
    </lightning-input>
    <!-- More input components -->
</template>
```

```javascript
handleOnChangeGeneric(event) {
    this[event.target.dataset.id] = event.target.value || event.target.checked;
}
```
