Question T10970
Visible to All Users

Dropdown choices from a custom array

created 3 years ago

I was wondering if it is possible to set choices in dropdown type question from my own array of objects.

Answers approved by surveyjs Support

created 3 years ago (modified 3 years ago)

Hello Moose,
The Dropdown question choices property accepts an array of objects with the following structure:

JavaScript
{ "value": any, // A value to be saved in the survey results "text": String, // A display text. This property supports Markdown. When `text` is undefined, `value` is used. "imageLink": String // A link to the image or video that represents this choice value. Applies only to Image Picker questions. "customProperty": any // Any property that you find useful }

If you wish to populate choices from a custom array, you can simply generate a new array with required properties and assign it to the question's choices property from code. Consider this example:

JavaScript
var myArr = [ {"myval": 0, "mytext": "Item 1"}, {"myval": 1, "mytext": "Item 2"}, {"myval": 2, "mytext": "Item 3"}, {"myval": 3, "mytext": "Item 4"} ]; var dropdownChoices = myArr.map((x) => ({ 'value': x.myval, 'text': x.mytext})); ... var survey = new Survey.Model(); const page = survey.addNewPage("page1"); const q1 = page.addNewQuestion("dropdown", "q1"); q1.choices = dropdownChoices; ...

Example.

Please let me know if you require further assistance.

    Comments (2)

      I find it confused where I am trying to add the choices in a existing question.

      I am using 1.9.37

      https://plnkr.co/edit/xbZcNouAAEaLH9dY

      however it works on this plnkr… so I am assuming 1.9.37 doesn't work? :o

        Hello Moose,
        The code actually works in v1.9.37. Please test this sample: https://plnkr.co/edit/y7rGiDvndU6H4DJA.

        Let me know how it goes.

        As a side question, would you please let me know if you considered an upgrade? v1.9.37 is 17 versions behind the current development so I believe you may get new features with upgrade.

        Thanks