0

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

2
  • Why are not you using the onchange handler? Commented Nov 11, 2020 at 8:25
  • Thanks for the reply Yes..that is possible, Is there a way of queryselector syntex to capture the specific input value. That way the code can be reduced.
    – Vishu
    Commented Nov 11, 2020 at 9:48

1 Answer 1

2

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;
        }
  }
1
  • Thank you for the help.
    – Vishu
    Commented Nov 11, 2020 at 9:47

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .