[SalesForce] How to get a data attribute inside an option of lightning:select component

I am trying to get the data-office value inside this component, when the user changes:

<lightning:select aura:id="Location" name="Location" onchange="{!c.locationHandler}">                     
              <aura:iteration items="{!v.locations}" var="loc"> 
                 <option
                      data-office="{!loc.Office_Contact_1__c}"                          
                      value="{!loc.Location_Code__c}">
               {!loc.Title__c}</option>
        </aura:iteration>

Inside my handler, I can get the value

event.getSource().get("v.value");

But I can't figure out how to get the value inside the attribute: "data-office". Any help please?

Best Answer

You can't get to it, at least not the way your code is written. Regardless, this still seems a lot more complicated than it should be. Here's a more practical version:

<aura:attribute name="selectedLocation" type="String" />
<lightning:select value="{!v.selectedLocation}" onchange="{!c.locationHandler}">                     
  <aura:iteration items="{!v.locations}" var="loc"> 
    <option value="{!loc.Id}">{!loc.Title__c}</option>
  </aura:iteration>
</lightning:select>

locationHandler: function(component, event, handler) {
  var locId = component.get("v.selectedLocation"),
      loc = component.get("v.locations").find(location => locId === location.Id),
      officeContact = loc && loc.Office_Contact_1__c;
  ...

Here, we just get the list back out, find the record we want, and, if one was selected (as opposed to none), we now have all the information we need from the record.

Related Topic