[SalesForce] Clear lightning-input and lightning-textarea on click

Looking to reset the two text fields labeled 'Name' and 'Description' when the 'Cancel' button is clicked. However, I'm getting the error ' [document.getElementById(…) is null]'. After some research, I've learned this error appears when the JS is within the same file as the HTML, but this JS is in a separate file and is nested within the button click, so the fields already exist. I've tried setting the value to a blank string, as well as resetting it using the .reset() method.

The HTML:

<lightning-input label="Name" id="nameInput" name="nameInput"></lightning-input>
<lightning-textarea label="Description" id="descriptionInput" name="descriptionInput"></lightning-textarea>
<lightning-button label="Cancel" onclick={cancelStep}></lightning-button>

The JS:

cancelStep(){
    document.getElementById('nameInput').value = '';
    document.getElementById('descriptionInput').value = '';
    //document.getElementById('nameInput').reset();
    //document.getElementById('descriptionInput').reset();
}

Best Answer

document.getElementById doesn't work in LWC or Aura; you cannot globally query elements, nor does the ID element work as you'd expect, as the runtime modifies it. Note that this applies only to Locker Service contexts, such as the Lightning Experience (LEX) and Communities, but does not necessarily apply to LWC OSS and other situations where Locker Service is not running.

Instead, you could write:

    [...this.template
        .querySelectorAll('lightning-input, lightning-textarea')]
        .forEach((input) => { input.value = ''; });

Where this.template.querySelectorAll gets elements by CSS selectors, [...array-like] converts the results to a proper array, and the forEach resets the value. You can be more specific, such as by class or parent selectors (e.g. just one form), but ID values are off the table.

Related Topic