How can I get the text of a selected choice in Javascript? | XM Community
Question

How can I get the text of a selected choice in Javascript?

  • 14 September 2019
  • 5 replies
  • 503 views

I'm trying to get the answer-text of a multiple choice question before submitting it.
Based on the provided API, I tried:
```javascript
foo = this.getSelectedAnswers();
```
This gives me an object but not the answer text. What I'm doing wrong?

5 replies

Userlevel 5
Badge +6
Hi @DRSK ,
I usually use something like this:

Qualtrics.SurveyEngine.addOnload(function()
{

var selectedRecode;

this.questionclick = function(event, element) {
if(element.type == "radio")
{selectedRecode = Number(this.getChoiceRecodeValue(this.getSelectedChoices()));
alert(selectedRecode);
}}
});
Userlevel 7
Badge +21

The following worked for me:
Qualtrics.SurveyEngine.addOnload(function()
{
    this.questionclick = function(event,element){
    if (element.type == 'checkbox')
    {
        var choiceNum = element.id.split('~')[2];
        var qNum = element.id.split('~')[1];
        var choiceRef = "#"+qNum+"-"+choiceNum+"-label > span";
        let choiceText = document.querySelector(choiceRef).innerHTML;
        Qualtrics.SurveyEngine.setEmbeddedData(choiceText,true);
        
       }



    }
});

Badge +1

Hi there!
I am trying to set as embedded data the text introduced in a text entry that I have allowed in a multiple choice answer.
I need to do it in the same question and, therefore, doing it using the piped text tool is not an option.
I know almost nothing about javascript, and I can't get the code you indicated to work. Should I do something to adapt it to my particular case?
What are the first two lines of your code exactly doing?
this.questionclick = function(event, element) {
if(element.type == "radio")
Thaaanks!


Userlevel 7
Badge +27

https://community.qualtrics.com/XMcommunity/discussion/comment/52720#Comment_52720That code creates an event handler. When someone clicks on the question it checks to see if the thing (i.e., element) they clicked on was a radio button. If it is, it executes the code in the if condition.
If you want to get the value of a text input, it won't work for you. You probably need to use an 'input' (as text is typed) or 'blur' (when respondent moves off text input) event handler instead of a 'click' handler.

Badge +1

https://community.qualtrics.com/XMcommunity/discussion/comment/52728#Comment_52728Hi TomG ,
Thanks for your quick response.
I thought the above code was intended to do what I need. Thanks for the clarification. Since it is not, I have openned a new discussion here:
https://community.qualtrics.com/XMcommunity/discussion/23201/how-to-get-a-text-entry-in-a-multiple-choice-answer-using-javascript/p1?new=1

Leave a Reply