Reset Lightning Input Fields in LWC

by Rijwan Mohmmed
0 comment

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 :

  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 :

	<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=""></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 class="slds-text-align_center">
			<lightning-button label="Reset Fields" onclick={handleReset} variant="brand"></lightning-button>

LWCFieldResetTechdicer.Js :

import { LightningElement } from "lwc";

export default class LWCFieldResetTechdicer extends LightningElement {
    this.template.querySelectorAll('lightning-input').forEach(element => {
      if(element.type === 'checkbox' || element.type === 'checkbox-button'){
        element.checked = false;
        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 :

  1. Salesforce LWC Inputs

You may also like

Leave a Comment