Set selected value dynamically in Picklist/lightning:select in lightning component.




How to set selected value dynamically in lightning select in salesforce lightning component ?

If you are developing something in lightning component then you must have face the situation to store selected value in your picklist.

Sometimes it works directly by setting the value in your lightning select. But if you are using a dynamic list and Key Value pair with an iteration to set the values, in that case setting value directly will not work.

We have to do some extra efforts with setting the value from controller. 

Please check the example below : 

In this example I am having a picklist of months and I want to change the selected value dynamically.

Component
1
2
3
4
5
<lightning:select value="{!v.selectedMonth}" aura:id="selectMonth" label="Select Month" onchange="{!c.changeMonth}">       
     <aura:iteration items="{!v.picklistValues}" var="item" indexVar="index">
         <option value="{!item.key}">{!item.value}</option>
     </aura:iteration>
 </lightning:select>

I have created a picklist in my component, in value I am having an attribute to store selected month.

I have a list of months in picklistValues attribute. And in option I am setting the key and values.

For example suppose in value I am having Jan, Feb, March and in key I have 1,2,3.

To set the selected value in selectedMonth attribute we have to set the value in it from controller and after that we just have to add a extra line in iterations option, Please check below example.


Component after setting the value

1
2
3
4
5
<lightning:select value="{!v.selectedMonth}" aura:id="selectMonth" label="Select Month" onchange="{!c.changeMonth}">       
    <aura:iteration items="{!v.picklistValues}" var="item" indexVar="index">
        <option value="{!item.key}" selected="{!item.key==v.selectedMonth}" >{!item.value}</option>
    </aura:iteration>
</lightning:select>

As you can see in above code we have added a new property in option and we have check it it is matching the current item's key.

It will set the value dynamically in your picklist.



If you have any question please leave a comment below.
If you would like to add something to this post please leave a comment below.
Share this blog with your friends if you find it helpful somehow !

Thanks
Keep Coding 


Post a Comment

0 Comments