1

I'm trying to get the value from a lightning:select but when I try a console.log in the js controller of the component, it doesn't show anything.

I put the same function exactly in 'Inspect Element > Console' and it works perfectly.

Component:

<lightning:select name="{!'mySelectedStatus' + case.CaseNumber}">
                                            <option text="All" value="" selected="true"/>
                                            <aura:iteration items="{!v.caseStatuses}" var="status">
                                                <option text="{!status}" value="{!status}" />
                                            </aura:iteration> 
                                        </lightning:select>

Controller.js:

changeStatus : function(component, event, helper) {
        var csNum = event.getSource().get("v.name");
        console.log(document.getElementsByName("mySelectedStatus00001044")[0].value); //Fails Here
        var status = document.getElementsByName("mySelectedStatus"+csNum)[0].value;

        helper.changeStatus(component, csNum, status);
    }

In the Inspect Element Console I get the result: document.getElementsByName("mySelectedStatus00001044")[0].value); Result => "New"

But in controller.js console.log() I get blank. Why?

Herohtar
  • 5,347
  • 4
  • 31
  • 41
  • 1
    `.get("v.name")` is asynchronous, the result hasn't be retrieved at the point you're trying to log it. See https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call/14220323#14220323 – Teemu Aug 23 '19 at 09:15
  • That is not the line that contains the error, in fact works perfectly, but Thank you. – Alex López Aug 26 '19 at 07:03

1 Answers1

0

Try something like this:

  1. Add attribue "label" on lightning:select as it is mandatory.

  2. Assign aura:id

  3. Define the onchange event to capture the latest changed value

    <aura:component>
        <aura:attribute name="test" type="String[]" default="['A','B']" />
        <lightning:select name="mySelectedStatus" label="selectlist" onchange=" {!c.changeStatus}" aura:id="mySelectedStatus">
            <option text="All" value="" selected="true"/>
            <aura:iteration items="{!v.test}" var="status">
                <option text="{!status}" value="{!status}" />
            </aura:iteration>
        </lightning:select>
    </aura:component>

JS Controller:

    changeStatus : function(component, event, helper) {
        console.log(component.find("mySelectedStatus").get("v.value"));
    }

Hope this helps!!!

Martyns
  • 3,605
  • 22
  • 33