[SalesForce] Reset the lightning-input to its default value

Problem – I am not able to reset the lightning-input to its default value.

What I want – I am providing the default value to lightning-input through my javascript file. I change the values of lightning-input on UI but then if I want my form back in the state as it was before, so I click "Reset" button which causes a javascript method to execute in which I reset my input fields using reset() method, but it doesn't work [ It does not set my lightning-input to their default values i.e. "Initial" and "0"].

Code –

In .html

<template>
    <form>
        <lightning-input type="text" 
                         name="input1" 
                         label="Enter some text" 
                         value={textValue} 
                         onchange={changeTextValue}>
        </lightning-input>
        <lightning-input type="number" 
                         name="input2" 
                         label="Enter some number" 
                         value={numValue}
                         onchange={changeNumValue}>
        </lightning-input>
        <lightning-button label="Reset" onclick={handleReset}></lightning-button>
    </form>
</template>

In .js

import { LightningElement, track } from 'lwc';

export default class Test extends LightningElement {
    @track textValue = "Initial";
    @track numValue = 0;

    changeTextValue(event) {
        this.textValue = event.target.value;
    }

    changeNumValue(event) {
        this.numValue = event.target.value;
    }

    handleReset() {
        const inputFields = this.template.querySelectorAll(
            'lightning-input'
        );
        if (inputFields) {
            inputFields.forEach(field => {
                field.reset();
            });
        }
    }
}

Best Answer

With a form, you can clear all values with:

handleReest() {
    this.template.querySelector('form').reset();
}

This will invoke the standard "HTML Form Reset" function. Note that the values won't go to the "default", just blank values. If you want to reset back to the initial values, you'd have to write the code again:

handleReset() {
    this.textValue = 'Initial';
    this.numValue = 0;
}
Related Topic