Search code examples
htmleventssalesforcesalesforce-lightning

Get data using div element's onclick event in iteration


I am trying to display clicked record in detail and I need clicked div's key value for that.

I tried using event.target.value, but it is giving me 0 as value.

HTML Code

<div class="slds-scrollable_y" style="height:300px">
    <template
        for:each={contacts.data}
        for:item="contact"
    >
        <div
            class="slds-p-top_small"
            key={contact.Id}
            onclick={handleContactClick}
            id={contact.Id}
        >
            <ul>
                <li class="slds-item">
                    {contact.Name}
                </li>
                <li class="slds-item">
                    {contact.Phone}
                </li>
            </ul>

            <div class="slds-p-top_small">
                <hr>
            </div>
        </div>
    </template>
</div>

Javascript file

import { LightningElement, track, wire } from 'lwc';
import searchContacts from '@salesforce/apex/ContactsListController.searchContacts'
export default class ContactList extends LightningElement {
    @track searchTerm = ''
    @track contacts
    @track selectedContact = ''
    @wire(searchContacts, { searchTerm: '$searchTerm' })
    loadContacts(result) {
        this.contacts = result
    }

    handleContactSearch(event){
        //Debounce the method
        window.clearTimeout(this.delayTimeout)
        const searchTerm = event.target.value;
        // eslint-disable-next-line @lwc/lwc/no-async-operation
        this.delayTimeout = setTimeout(() => {
            this.searchTerm = searchTerm
        }, 300)
    }

    handleContactClick(event){
        // eslint-disable-next-line no-console
        console.log(event.target.value);
        this.selectedContact = event.target.value;
    }

    checkIfEmpty(){
        // eslint-disable-next-line eqeqeq
        return this.selectedcontact == '';
    }
}

I expected event.target.value to provide contact's id but it is returning 0.


Solution

  • You should try to use the id of the clicked <div>:

    handleContactClick(event){
        // eslint-disable-next-line no-console
        console.log(event.currentTarget.id);
        this.selectedContact = event.currentTarget.id;
    }
    

    Update

    Replaced target with currentTarget according to the comment