[SalesForce] How to get the selected value of a picklist field in lightning combo box using template.getQuerySelector

How to get the selected value of a picklist field in lightning combo box using template.getQuerySelector?.

<lightning-combobox label={firstControllingFieldLabel}
                            name="Controlling Picklist Type"                                 
                            options={optionValuesFirstSet.controlling}
                            onchange={handleControllingFirstChange}
                            placeholder="None" 
                            value={selectedValuesFirstSet.controlling}
                            >
        </lightning-combobox>   

For the above code i want to get the value i am selecting from UI using template.getQueryLocator?

i tried using below snippet:

 let typeOfCase = this.template.querySelector("[name='Controlling Picklist Type']");
        console.log('test type of case',typeOfCase);

But does not work. Any help please?

Best Answer

You need to use the data-id attribute instead of the name attribute. You can find an explanation for why name doesn't work here. Also, when you use query selector, you will be returned the whole element. In order to get the value in the combobox, you need to use .value. Checking to make sure an element is returned before calling .value will prevent an error from being thrown.

<lightning-combobox label={firstControllingFieldLabel}
                            data-id="Controlling Picklist Type"                                 
                            options={optionValuesFirstSet.controlling}
                            onchange={handleControllingFirstChange}
                            placeholder="None" 
                            value={selectedValuesFirstSet.controlling}
                            >
        </lightning-combobox>
let combobox = this.template.querySelector("[data-id='Controlling Picklist Type']");
let typeOfCase = combobox ? combobox.value : null;
console.log('test type of case', typeOfCase);

It's unclear what you are trying to accomplish using query selector. Is it possible that you can just use the value variable? The variable can be set in your onchange event handler. See this example in the combobox documentation.