Question T11490
Visible to All Users

Add choices form api to checkbox questions

created 2 years ago (modified 2 years ago)

Hello

Is it possible to add new choices to a checkbox question from api code in which there are already choices, because it tries to add new choices (
``survey.getQuestionByName("xxx").choices = [{
"value": "x1",
"text": "x 1"
},
{
"value": "x2",
"text": "x2"
}];```),

I want to add choice to question:

Code
"type": "checkbox", "name": "xxx", "title": "text text", "isRequired": true, "choices": [ { "value": "y1", "text": "y 1" }, { "value": "y2", "text": "y 2" }, ] },

because it adds new choices to the existing ones, the old ones disappear

Regards
Matt

Answers approved by surveyjs Support

created 2 years ago (modified 2 years ago)

Hello Matt,
The following code replaces existing choices with new ones:

JavaScript
survey.getQuestionByName("xxx").choices = [{ "value": "x1", "text": "x 1" }, { "value": "x2", "text": "x2" }];

If you wish to add new choices to existing ones, first create an array of ItemValue values and then merge an existing choices array with a new one. Consider this code:

JavaScript
const newChoices = [{ "value": "x1", "text": "x 1" }, { "value": "x2", "text": "x2" }]; const newChoiceItems = []; newChoices.forEach(x => { newChoiceItems.push(new Survey.ItemValue(x.value, x.text)); }) var question = survey.getQuestionByName('xxx'); const newChoiceArray = [...question.choices, ...newChoiceItems]; question.choices = newChoiceArray;

Example.

Please let me know if you have any questions or require further assistance.

    Comments (2)

      Perfect, thank you very much :)

        My pleasure. Please feel free to contact us if you have any questions.