Dynamically update Lookup Column

Is it possible to dynamically set a lookup column on button click?
I thought something like fd.field(‘Site’).$el.innerText.value=“PTG”;
would work but it does not seem to work.
I also thought passing the ID would work but that does not seem to work either. Please help.
Thank you

Hi!

Sure, please use this code:

fd.field('Site').widget.value(3);

Notice that ‘3’ is an ID of your lookup value.

How it is possible to select a element in a lookup field based on a text value and not the ID?

Dear phil,

Yes, it’s possible, though you should retrieve lookup options with JS, then go through them, find a match, and set it with a matching item ID.

A code will be like this:

fd.field("Lookup").ready().then(function(field){    
    field.widget.bind("dataBound", function() {
        var lookups = field.widget.dataSource.data();
        for (i = 0; i < lookups.length; i++) {
            if (lookups[i].LookupValue == "Your text value") {
                field.value = lookups[i].LookupId;
                break;
            }
        }
    })  
}) 

Notice that you should replace “Your text value” with your text value, “Lookup” with the internal name of your lookup field and place this code snippet into the spRendered() event handler.

Thanks a lot! Works fine …

Hi AlexZver

I have a similar issue. Currently I apply a filter to my lookup field so users can only see options applicable to them. I would like to enhance this by automatically selecting the first option in the lookup when they create a new item. My code below is based on your example, but seems to be applied before the filter is applied. Any advice on this?

fd.field('Site_x0020_Name').ready().then(function(field) {      
    field.filter = 'RGM/Id eq ' + _spPageContextInfo.userId;
    field.widget.dataSource.read();

    field.widget.bind("dataBound", function() {
        var lookups = field.widget.dataSource.data();
        field.value = lookups[0].LookupId;
    })
})

Dear Andre,

“field.widget.dataSource.data();” returns all the items from the lookup without filtering, you should manually apply the filter to the array of lookups by JavaScript.

Thank you Alex.
For some reason my code now work as expected without making any changes.

i tried the same to set look up column value not working

@ShantiBhattarai,

Please use this code to set lookup field value. Note that 3 is the ID of the lookup value.

fd.field('Lookup').value = 3;

this didnt work either but i got it working using inside the ready function

1 Like