1

I am very new to LWC and Javascript. I have an LWC component with a search bar and a table (created in HTML file) showing the search result. I want to add another column in the table with a button on each row which allows me to add that whole row into another table in other component.

This is my HTML file.

'  <template>
   <lightning-card title="Account Search Bar" icon-name="standard:account">
    <lightning-input type="search" onchange={handleKeyChange} class="slds-m-bottom_small" label="Search"
        value={accountName}>

    </lightning-input>
    <table id="table">
        <thead>
            <tr>
                <th class="" scope="col">
                    <div class="slds-truncate" title="Account Name">Name</div>
                </th>
                <th class="" scope="col">
                    <div class="slds-truncate" title="Account Phone">Phone</div>
                </th>
                <th class="" scope="col">
                    <div class="slds-truncate" title="Select Account">Select Account</div>
                </th>
            </tr>
        </thead>
        <tbody>
            <template for:each={accountList} for:item="accountObj" for:index="index">
                <tr class="table" key={accountObj.Id}>
                    <td class="name">{accountObj.Name}</td>
                    <td class="phone">{accountObj.Phone}</td>
                    <td class="addButton"><input type="submit" value="Add" onclick={addField}></td>
                </tr>
            </template>
        </tbody>
    </table>

</lightning-card>

'

I have added the buttons nd I am trying to get the data of the row from which the button is clicked. But I am getting 'undefined' in every object.

This is my js file.

 import { LightningElement,wire,track } from 'lwc';
 import getAccounts from '@salesforce/apex/AccountSearchCls.getAccounts';
 const DELAY = 300;
 export default class TestComponentSearch extends LightningElement {
 accountName='';
 @track accountList =[];
 @track buttonId=1;
 @wire(getAccounts,{actName:'$accountName'}) 
 retrieveAccouts({error,data}){ 
    if(data){
        this.accountList = data;
    }
    else if(error){

    }
 }
 handleKeyChange(event){
     const searchString= event.target.value;
     window.clearTimeout(this.delayTimeout);
     this.delayTimeout = setTimeout(()=>{
         this.accountName =searchString;
     },DELAY);
 }

 addField()
 {
     console.log("In addField");
     var table = document.getElementById('table');
     selected = table.getElementsByClassName('tbody')[0];
     var rows= selected.getelEmentsByTagName('tr');
 }
}

I am not sure what is the problem or if this is the right way to do it. I would appreciate if anyone helps me in it.

Niklaus
  • 39
  • 1
  • 9

2 Answers2

0

Add an event parameter to addField method get the selector from which the button was clicked and try to find the parent row using the table class that you have defined already and process the columns using innerText.

addField(event)
{
        let rows=event.target.closest("tr.table");
        let cols=rows.querySelectorAll('td');
        let name=cols[0].innerText;
        let phone=cols[1].innerText;
        alert('Name :'+name+' Phone :'+phone); 
}
Kamal
  • 486
  • 1
  • 6
  • 14
0

I am not sure about your complete use case. But, the use case you mentioned is achievable through lightning base components and no need to use table tags.

HTML markup

    <lightning-input type="search" value={searchStr} onchange={searchChangeHandler}>
    </lightning-input>

    <lightning-datatable columns={columns} data={data} key-field="Id"
        onrowaction={handleRowAction}>
    </lightning-datatable>

</template>

Javascript code

// MyScratchComp.js

import { LightningElement, wire } from 'lwc';
import getAccounts from '@salesforce/apex/LWCHelper.getRecords';

export default class MyScratchComp extends LightningElement {

    data;

    connectedCallback() {
        this.initDefaultValues();
        this.getData();
    }

    initDefaultValues() {
        this.searchStr = 'Test';

        this.columns = [{
            label : 'Name',
            fieldName : 'Name',
            type : 'Text'
        },{
            label : 'Industry',
            fieldName : 'Industry',
            type : 'Text'
        },{
            label : 'PhotoURL',
            fieldName : 'PhotoUrl',
            type : 'Text'
        },{
            label : 'Action',
            type : 'button',
            typeAttributes : {
                label : 'click here'
            }
        }];
    }

    searchChangeHandler(event) {
        this.searchStr = event.target.value;
        this.getData();
    }

    async getData() {
        try {
            this.data = await getAccounts(
                {
                    searchQuery : `Select Id, Name, Industry, PhotoURL From Account Where name like '%${this.searchStr}%' LIMIT 10`
                }
            );
        }
        catch(e) {
            console.error(JSON.stringify(e));
        }
    }

    handleRowAction(event) {
        alert('Row selected - ' + JSON.stringify(event.detail.row));
    }
}

Apex code

/* LWCHelper Apex class */
public with sharing class LWCHelper {

    @AuraEnabled
    public static List<SObject> getRecords(String searchQuery){
        try {
            return Database.query(searchQuery);
        } catch (Exception e) {
            throw new AuraHandledException(e.getMessage());
        }
    }
}