How can I set a value in a multiple choice checklist through javascript

Is there a way to set the multiple-choice checkbox value(s) through javascript?

Multiple-choice variables and database fields are represented as an array in JS. The states it can be in, in JS, is either null/undefined; an empty array [], or an array of 'keys' that map to the selected options.

So, let's assume a view variable:

<var name="color_choices" type="multiple-choice" >
  <option key="red">RED</option>
  <option key="green">GREEN</option>
  <option key="blue">BLUE</option>
</var>

Then in your js you could set the variable as follows:


function setColorChoices() {
  view.color_choices = ["red"];
  // OR
  view.color_choices = ["red", "green"];
  // OR
  view.color_choices.pop(); // this assumes view.color_choices is already an array and not null/undefined
  view.color_choices.push("blue");
}

However, if you want to dynamically change the values that are displayed to the user in the view component, and not necessarily change which values are selected (as per the example code above), then that is not currently possible. In this case, if you want to create a dynamic list of multi-selectable things from JS then you will need to use database objects for that.

I hope this helps

2 Likes

Thanks that helped