+ Start a Discussion
Emilien Guichard 59Emilien Guichard 59 

get lightning:select selected value in controller

Hello there,

I am having a hard time trying to get lightning:select component selected value in controller :

Here is my code :
component :
<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId" access="global" >
    
        <!-- handlers-->
        <aura:handler name="init" value="{!this}" action="{!c.init}"/>
    
            <lightning:select name="distance" label="Distance ?" onchange="{!c.onChange}">
                <option value="10km">10</option>
                <option value="25km">25</option>
                <option value="50km">50</option>
                <option value="100km">100</option>
            </lightning:select>
           
</aura:component>
controller:
({
     
init: function (component, event, helper) {
    
    	console.log('distance ' + component.find("distance").get("v.value"));

    },
    
    onChange: function (component, event, helper) {
    	console.log(component.find("distance").get("v.value"));
    }
})
wheh the page loads or when I change the picklist value, I get his error message :
 
Action failed: c:map$controller$init [component.find(...) is undefined]

Thanks a lot for your help !

 
Best Answer chosen by Emilien Guichard 59
Alain CabonAlain Cabon
Hello,

component.find("distance")  : it is not the name but "aura:id"

<lightning:select aura:id="distance"

https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/js_cb_find_by_id.htm

All Answers

Alain CabonAlain Cabon
Hello,

component.find("distance")  : it is not the name but "aura:id"

<lightning:select aura:id="distance"

https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/js_cb_find_by_id.htm
This was selected as the best answer
Emilien Guichard 59Emilien Guichard 59
Thanks Alain,

Now I don't have the error message anymore but the first log is returning : distance undefined
but when I change the picklist value the value is displayed correctly

Do you have any why I can't display the value by default at first ?
Alain CabonAlain Cabon
Emilien,

For the default value, you can use the init function and set value.
 
init: function (component, event, helper) {    
    	console.log('distance ' + component.find("distance").get("v.value"));

        component.find("distance").set("v.value","50km");

 },

A+
Alain
Emilien Guichard 59Emilien Guichard 59
Thanks a lot Alain, it does the trick !
SijuSiju
Component
<lightning:select name="distance" label="Distance ?" onchange="{!c.onChange}" aura:id="distance">
                <option value="10km">10</option>
                <option value="25km">25</option>
                <option value="50km">50</option>
                <option value="100km">100</option>
            </lightning:select>
JSController
var selectedValue=  component.find("distance").get("v.value");
alert("selectedValue:"+selectedValue);