Getting value of specified field in lightning record edit form

lightninglightning-recordeditformqueryselector

Can you please help with below issue. i am trying to get name of field or key of lighting record form when phone number is changed. Every time when i try to print the name it's giving name of very first instance of lightning record form. You can consider this data as input.

listofRecords = [{Id : 'salesforceId1',
                 name_field__c : 'Test1',
                 phone : '23456786332'},
                  {Id : 'salesforceId1',
                 name_field__c : 'Test1',
                 phone : '23456786332'},
                  {Id : 'salesforceId1',
                 name_field__c : 'Test1',
                 phone : '23456786332'}]

html code :

<template>
<template for:each = {listofRecords} for:item = "r1">
 <lightning-record-edit-form
            record-id={r1.Id}
            object-api-name={objectApiName}
            onsuccess={handleSuccess}>
            <lightning-input-field field-name="name_field__c" data-id="name_field__c"></lightning-input-field>
            <lightning-input-field field-name="Phone_field__c" data-id="Phone_field__c" onChange="handleChange"></lightning-input-field>
    </lightning-record-edit-form>
</template>
</template>

java script code :

import { LightningElement, api } from 'lwc';

export default class LwcRecordViewForm extends LightningElement {
   handleChange(event){
       let namefield = this.template..querySelector('[data-name="name_field__c"]');
       // print key of lightning record form or corresponding name of changed phone
}

Thanks

Best Answer

querySelector returns just the first matching element--you're getting exactly what you asked for. Instead, you can read the value from event.target.value:

let phoneNumber = event.target.value;

If you also need to know what row it was from, you can add:

<template for:each = {listofRecords} for:item = "r1" for:index="index">

...

<lightning-input-field field-name="Phone_field__c" 
  data-id="Phone_field__c" 
  data-index={index}
  onChange="handleChange">
</lightning-input-field>
Related Topic