TransWikia.com

How to fetch the value of Lightning input having specific name

Salesforce Asked by Vishu on December 2, 2020

I wanted to fetch the value of the Input element by specifying name of the element.
i do have 2 input element but i need to fetch the value of input with name=’press’

How can i modify my below code.

enter image description here

enter image description here

One Answer

You are trying to access the field value on button click using querySelector, but you cannot use name attribute to identify a particular lightning input field inside querySelector. You can make use of dataset attribute to do so.

Instead of name, change it to data-name in input markup definition.

    <div class="slds-col">
        <lightning-input type="number" data-name="temp"  label="Enter a Temperature" ></lightning-input>
    </div>
    <div class="slds-col btnMargin">
        <lightning-button variant="brand" label="Check" title="Check" onclick={handleLusmSearch} class=""></lightning-button>
    </div>

In JS side, You can access it like:-

handleLusmSearch(event){
    const temp = this.template.querySelector('lightning-input[data-name="temp"]').value;
    console.log(temp);
}

If you want to get the field value on change of field value, you can make use of onchange handler. The sample code would be:-

HTML

<lightning-input name="numberField" type="number" onchange={handleChange} label="Enter a number"></lightning-input>
<lightning-input name="checkboxField" type="checkbox" onchange={handleChange} label="Basic option"></lightning-input>

JS

 numberFieldValue;  
 checkBoxFieldValue; 
 handleChange(event){
        var value;
        if(event.target.type === 'checkbox' || event.target.type === 'checkbox-button' || event.target.type === 'toggle'){
            value = event.target.checked;
        }else{
            value = event.target.value;
        }
        if(event.target.name === 'numberField'){
            this.numberFieldValue = value;
        }else if(event.target.name === 'checkboxField'){
            this.checkBoxFieldValue = value;
        }
  }

Answered by sanket kumar on December 2, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP