Hey friends, today we are going to discuss in this post how to Reset Lightning Input Fields in LWC on button click dynamic JavaScript method function in Lightning Web Component (LWC).
Also check this: Notifications with New Alert, Confirm, and Prompt in LWC
Key Highlights :
- We will create a custom form with lightning fields.
- Create a Reset button to reset all the fields.
- We will cover all types of fields in this form.
Code :
LWCFieldResetTechdicer.HTML :
<template>
<lightning-card title="Reset Input Field Techdicer" icon-name="standard:recipe">
<div class="slds-p-around_small">
<lightning-input type="text" label="First Name" data-id="form" value="Techdicer"></lightning-input>
<lightning-input type="text" label="Last Name" data-id="form" value="Techdicer"></lightning-input>
<lightning-input type="email" label="Email" data-id="form" value="techdicerkeeplearning@gmail.com"></lightning-input>
<lightning-input type="number" label="Amount" data-id="form" formatter="currency" value="200"></lightning-input>
<lightning-input type="date" name="Date" label="Date" value="2020-09-07" data-id="form"></lightning-input><br/>
<lightning-input type="checkbox" label="Is Agree ?" data-id="active" checked></lightning-input>
</div>
<div class="slds-text-align_center">
<lightning-button label="Reset Fields" onclick={handleReset} variant="brand"></lightning-button>
</div>
</lightning-card>
</template>
LWCFieldResetTechdicer.Js :
import { LightningElement } from "lwc";
export default class LWCFieldResetTechdicer extends LightningElement {
handleReset(){
this.template.querySelectorAll('lightning-input').forEach(element => {
if(element.type === 'checkbox' || element.type === 'checkbox-button'){
element.checked = false;
}else{
element.value = null;
}
});
/* you can also reset one by one by id
this.template.querySelector('lightning-input[data-id="form"]').value = null;
this.template.querySelector('lightning-input[data-id="form"]').checked = false;
* */
}
}
Output :
Reference :
What’s your Reaction?
+1
2
+1
+1
+1
+1
+1