Select option based on label not value | XM Community
Solved

Select option based on label not value


Badge +3

Hello,

Could anyone help me with the JS syntax for selecting an option based on it’s name/label, rather than it’s value?

e.g. if option 1 has the value of 1 and the label ‘Brand1’, the below script correctly selects option 1, using the value=1 reference. 

this.setChoiceValueByRecodeValue(1, true); 

 

But how do I rewrite it to instead reference ‘Brand1’? 

I tried using this code, but it doesn’t seem to work…

this.setChoiceValueByLabel('Brand1', true);

 

Is there something that I am missing here?

 

Thanks.

 

icon

Best answer by ahmedA 4 March 2024, 07:13

View original

11 replies

Userlevel 7
Badge +36

Hi @cgillon 

You need to use the below code for labels

this.setChoiceValueByVariableName('Brand1',true)

Please make sure you enable variable names for your choices.

FYI Source:api.qualtrics.com/ZG9jOjIwMTY2NzUy-javascript-question-api

Badge +3

Hi Deepak,

Thanks for the reply.

When you say to “enable variable names for your choices”, do you mean to turn on the ‘Variable Naming’ in the ‘Recode Values’ screen?

I turned on the recoding, and tried that code, but it didn’t pre-select ‘Brand1’ when I previewed the question. Is there any other setting that might be stopping this from working?

 

Regards,

Craig

 

Userlevel 7
Badge +36

Hi Deepak,

Thanks for the reply.

When you say to “enable variable names for your choices”, do you mean to turn on the ‘Variable Naming’ in the ‘Recode Values’ screen?

I turned on the recoding, and tried that code, but it didn’t pre-select ‘Brand1’ when I previewed the question. Is there any other setting that might be stopping this from working?

 

Regards,

Craig

 

Yes please enable variable naming

Userlevel 7
Badge +21
this.setChoiceValue(Object.entries(this.getQuestionInfo().Choices).filter((a) => a[1].Text == "BRAND NAME")[0][0], 1);

 

Badge +3

Yes, that is what I did, but ‘Brand1’ remained un-check..

Is the above screenshot correct?

 

Userlevel 7
Badge +36

@cgillon Can you show how you have added the code as it does work for me?

Badge +3

Hi Deepak,

I just pasted it right in…

 

Badge +3

NB: tried both...

  • this.setChoiceValueByVariableName('Brand1',true)
  • this.setChoiceValueByVariableName(“Brand1”,true)

But neither worked.

Userlevel 7
Badge +36

Not sure what’s the issue as the code does work for me try in any other survey project and check if something else is causing the issue.

Badge +3

I was on ‘Flat’ layout, but switching to Simple didn’t make the code work.

Badge +3
this.setChoiceValue(Object.entries(this.getQuestionInfo().Choices).filter((a) => a[1].Text == "BRAND NAME")[0][0], 1);

 

Thank you for this piece of script. It looks to do what I was trying to achieve, but I’m unsure as to what this is doing, and why it succeeded where the simpler script failed (particularly since the failure seems to be limited to my survey version)

Leave a Reply