How can you get the inputs directly without using the onchange event?

Till now, we have seen when we want to capture the value of input fields, we have used “onchange” event into the input fields just like

<lightning-input label="Department" onchange={handleChange} class="slds-m-bottom_x-small"></lightning-input>

In this “onchange” event procedure, always we are sending the values from input fields to JS file.

Is there any way to get the values of the input fields in a single shot?

The answer is YES. We can use querySelector() JS function to get a value in a single shot.

Let’s say, we have built a component named “takeUserInput“.

Step 1: As per previous examples, we need to update the “takeUserInput.js-meta.xml” file to set the visibility in Lightning App Builder.


<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="" fqn="takeUserInput">

Step 2: Need to write the respective HTML file.


    <lightning-card title="Take User Inputs in a Single Shot" icon-name="standard:contact">
        <div class="slds-p-around_small">
            <lightning-input label="First Name" data-field="FirstName" class="slds-m-bottom_x-small"></lightning-input>
            <lightning-input label="Last Name" data-field="LastName" class="slds-m-bottom_x-small" required></lightning-input>
            <lightning-button label="Get Values" variant="brand" onclick={takeInputs}></lightning-button>
            <div class="slds-p-top_small">
                Name: {name}

Here, we have defined an attribute as data-field for all the input fields. Through this attribute,data-field, we will capture the input fields directly.

Step 3: Now, we need to work on the JS file.


import { LightningElement,track } from 'lwc';

export default class TakeUserInput extends LightningElement {

    @track name;

        this.firstName = this.template.querySelector("[data-field='FirstName']").value;
        this.lastName = this.template.querySelector("[data-field='LastName']").value; = this.firstName + " " + this.lastName;


We have used template.querySelector() JS function in which we have passed the data-field to denote the particular input field and get the value using “this.template.querySelector(“[data-field=’FirstName’]”).value” notation in a single shot.

Step 4: At last, need to add this LWC into Lightning App/Home or Record Page.


20,099 total views, 3 views today

Rating: 5.0/5. From 6 votes.
Please wait...
This entry was posted in Lightning Web Component. Bookmark the permalink.

Leave a Reply