Reset Lightning Input Fields in LWC

by Rijwan Mohmmed
0 comment
reset-lightning-input-fields-in-lwc-techdicer

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

reset-lightning-input-fields-in-lwc-output-techdicer
reset-lightning-input-fields-in-lwc-output-techdicer

Key Highlights :

  1. We will create a custom form with lightning fields.
  2. Create a Reset button to reset all the fields.
  3. 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 :

reset-lightning-input-fields-in-lwc-output-techdicer
reset-lightning-input-fields-in-lwc-output-techdicer

Reference :

  1. Salesforce LWC Inputs
What’s your Reaction?
+1
2
+1
0
+1
0
+1
0
+1
0
+1
0

You may also like

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.