1

Work on LWC. Why I can not get the data item on the li onclick event?

<template>
    <li role="presentation" key={item.key} class={itemClass} id="ms-list-item" data-id={item.key} data-name={item.value} onclick={onItemSelected}>
        <div id="listbox-option-unique-id-01"  class="slds-media slds-listbox__option slds-listbox__option_plain slds-media_small slds-media_center" role="option">
            <span class="slds-media__figure">
                <lightning-icon icon-name="utility:check" size="x-small" alternative-text="Selected" class="slds-icon slds-icon--selected slds-icon--x-small slds-icon-text-default slds-m-right--x-small"></lightning-icon>
            </span>

            <span class="slds-media__body">
                <span class="slds-truncate" title={item.value}>{item.value}</span>
            </span>
        </div>
    </li>
</template>

Js file

import { LightningElement, track, api } from 'lwc';
export default class PickListItem extends LightningElement {
    @api item;

    constructor () {
        super();
    }
    connectedCallback () {
        this._item =  JSON.parse(JSON.stringify (this.item));
    }
    get itemClass () {
        return 'slds-listbox__item ms-list-item' + (this.item.selected ? ' slds-is-selected' : '');
    }
    onItemSelected (event) {
        let temp=event.target.dataset.name
        console.log('onItemSelected:::',JSON.stringify(temp));
    }
}

Always get console output onItemSelected::: undefined

2
  • I don't think you can split the key inside the component and the for:each directive outside the component (e.g. in a parent component) the way you're going about it. This is likely the cause of any of a number of issues. This child component should not be aware of if it is being placed inside a for:each directive or not. You'll need to shuffle some of your code around.
    – sfdcfox
    Sep 20, 2020 at 16:40
  • 1
    Try changing event.target to event.currentTarget. Sep 20, 2020 at 17:32

1 Answer 1

2

We can retrieve the custom data attribute from an event using dataset property or getAttribute() method. Let's assume the api property "item" has value

item = { "key" : "value" };

<li> element contains data-id={item.key}, for <li> element onclick method onItemSelected()

onItemSelected (event) {
    let temp=event.currentTarget.dataset.id
    console.log('onItemSelected:::',temp);
    let tempCopy=event.currentTarget.getAttribute("data-id");
    console.log('onItemSelected:::',tempCopy);
}

this should give below highlighted value, from lwc playground enter image description here

You must log in to answer this question.

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