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.

takeUserInput.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="takeUserInput">
    <apiVersion>45.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

Step 2: Need to write the respective HTML file.

takeUserInput.html

<template>
    <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}
            </div>
        </div>
    </lightning-card>    
</template>

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.

takeUserInput.js

import { LightningElement,track } from 'lwc';

export default class TakeUserInput extends LightningElement {

    firstName;
    lastName;
    @track name;

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

        this.name = 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.

Result

20,485 total views, 3 views today

Rating: 5.0/5. From 6 votes.
Please wait...

You may also like...