0

I want to store both Value & Label attribute upon clicking particular Combo-box value, but currently I am only able to get Value.

When I try to store & print Label - it says undefined.

enter image description here

Here is the PLAYGROUND LINK.

1
  • 3
    Possible duplicate here
    – Shamina
    Commented Dec 23, 2019 at 11:44

2 Answers 2

2

Use below code to fix the issue:

handleChange(event) {
        this.value = event.detail.value;
        let selectedObjectlabel  = event.target.options.find(opt => opt.value === event.detail.value).label;
        console.log('Label ->' + selectedObjectlabel);
    }

Output

enter image description here

1

For value attribute store values in JSON String format Like { label: 'New', value: '{"label" : "New", "value":"1"}' }

In handleChange Method convert JSON String to object and access label and value properties of that object.

Code Snippet.

basic.html

<template>
    <lightning-combobox
            name="progress"
            value={value}
            placeholder="Select"
            options={options}
            onchange={handleChange} ></lightning-combobox>

    <p>Selected value is: {value}</p>
</template>

basic.js

import { LightningElement, track } from 'lwc';

export default class ComboboxBasic extends LightningElement {
    @track value = 'inProgress';

    get options() {
        return [
            { label: 'New', value: '{"label" : "New", "value":"1"}' },
            { label: 'In Progress', value: '{"label" : "In Progress", "value":"2"}' },
            { label: 'Finished', value: '{"label" : "Finished", "value":"3"}' },
        ];
    }

    handleChange(event) {
        let v = JSON.parse(event.detail.value);
        console.log('Label - ' + v.label);
        this.value = v.value;
    }
}

Playground link - https://developer.salesforce.com/docs/component-library/tools/playground/x0iNRAPJ/1/edit

1
  • That's extremely complicated and overkill. There are better ways to handle this (see the other answers).
    – sfdcfox
    Commented Dec 23, 2019 at 13:34

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