10

I'm developing a LWC Combobox and I want to get the label of the selected value in the handleChange() method, not the id. I filled the combobox with JSON Items in this form :

{value :'Id', label:'Label'}

I used this in JS : event.detail.value but it gives the id not the Label.

1
  • I tried that before but event.detail.label is undefined. I have a solution in my mind which consist of storing all the items (id,label) in an array and as I can get the id of the selected value, I can find the corresponding label from the array, but this solution is very onerous. Commented Sep 19, 2019 at 10:45

2 Answers 2

24

You do not have direct way of getting label (as you get only selected value in event.detail). You need to depend on all options (simply get it from event.target) and filter based on selected value. You can use below:

JS:

@track selectedLabel;

get options() {
    return [
        { label: 'New', value: 'new' },
        { label: 'In Progress', value: 'inProgress' },
        { label: 'Finished', value: 'finished' },
    ];
}

handleChange(event) {
    this.selectedLabel = event.target.options.find(opt => opt.value === event.detail.value).label;
}

HTML:

<lightning-combobox name="progress"
                        label="Status"
                        placeholder="Select Progress"
                        options={options}
                        onchange={handleChange}></lightning-combobox>

    <p>Selected label is: {selectedLabel}</p>
2
  • 3
    It works, Thank you @salesforce-sas. Commented Sep 19, 2019 at 10:49
  • 1
    Yeah, that's correct ^ Commented Sep 19, 2019 at 10:51
6

Another way to get the label, iterate with options and match the value to find the label.

   statusOptions = [
        {value: 'new', label: 'New'},
        {value: 'in-progress', label: 'In Progress'},
        {value: 'finished', label: 'Finished'}
    ];

    handleChange(event) {
        const selectedOption = event.detail.value;
        var currentLabel =  this.statusOptions.filter(function(option) {
                               return option.value == selectedOption;
                            })
        if(currentLabel)
          //get the label
          console.log(currentLabel[0].label)

    }
1
  • Yeah this works to but i prefer @salesforce-sas is solution. Thank you ^^ Commented Sep 19, 2019 at 14:49

You must log in to answer this question.

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