2

I would like to get the value of the label of the selected drop down item.

In this case, the label is the Name of the Contact.

<aura:component>

<aura:attribute name="contacts" type="Contact[]"/>

<lightning:select label="Contact" aura:id="contactList" name="contactList">

   <aura:iteration items="{!v.contacts}" var="c" indexVar="index">
       <option value="{!c.Id}">{!c.Name}</option>
   </aura:iteration>

</lightning:select>

</aura:component>

I know how to get the value:

component.find("contactList").get("v.value");

But how do I get the label?

2 Answers 2

9

Strictly speaking, you can't get the label, because the child elements are hidden away from you ("Locker Service"). If you just want the name of the contact, you can do something like this:

var contacts = component.get("v.contacts"), 
    value = component.find("contactList").get("v.value"),
    index = contacts.findIndex(item => item.Id == value),
    contactName = index >= 0? contacts[index].Name: null;

If you're still supporting IE 11, you can't use findIndex:

var contacts = component.get("v.contacts"), 
    value = component.find("contactList").get("v.value"),
    index, contactName;
contacts.forEach(function(v,i,a) { 
    if(v.Id == value) {
        index = i;
    }
});
contactName = contacts[index].Name;
2
  • Hi Fox, followup question: your solution here will work if the `<option value="A Unique Id">.. but what if the option values are not guaranteed unique, yet may have different labels?
    – smohyee
    Commented Dec 3, 2018 at 22:05
  • @smohyee The value should be unique, because that is how the select list is designed to work. I'm not just talking about Lightning here, I'm talking about HTML in general. Choose a value that is unique from all other values in the list.
    – sfdcfox
    Commented Dec 4, 2018 at 0:24
0

For getting the value you should use the data-value="{!c.Id}"

Component Code 
<option value="{!c.Id}" onclick="{!c.getVal}">{!c.Name}</option>

controller.js
fun:getVal(cmp, evt, helper) { 
var ctarget = event.currentTarget;
var id_str = ctarget.dataset.value;
// here you getting the value in Id_str
}

You must log in to answer this question.

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