2

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.

  • 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. – Aymane Hammioui Sep 19 '19 at 10:45
10

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>
| improve this answer | |
2

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 =  statusOptions.filter(function(option) {
                               return option.value == selectedOption;
                            })
        if(currentLabel)
          //get the label
          console.log(currentLabel[0].label)

    }
| improve this answer | |
  • Yeah this works to but i prefer @salesforce-sas is solution. Thank you ^^ – Aymane Hammioui Sep 19 '19 at 14:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.