Resources on Arrays?

What is the best way to store and use data collected from check boxes? I am assuming I would use array’s where I can store multiple results in one field? I am a bit unfamiliar with how this is done. Anyone could point me in the right direction?

Example:
Let’s say I have the following colors:
Red
Orange
Yellow
Green
Blue

How do I store this information in a single field labeled “colors” if a user can select multiple colors?

You’ll need a bit of JavaScript for it.
It’s probably best to format as a JSON object and push them to into a text field.
Here is how you could get the formatting bit done:

	let j = {};
	$w('Checkbox').forEach(function(c){
			j[c.value] = c.checked;
	});

	console.log(j);

that assumes you want all the checkboxes on the page.
Otherwise you could explicitly state which ones you want like so:

$w('#checkbox1,#checkbox2,#checkbox3').forEach(function(c){

Uval – Appreciate the response. I am getting an error, says “forEach” is undefined.

I’m learning the basics of Wix Code Javascript, but hopefully you can bear with me. Essentially, once we get this code up and running I could just write the rest of the code to insert “j” into the dataset and I am good to go?

Hey David,

Maybe we can turn this around? Have you considered having 5 Boolean fields in Content Manager for each of these colors (Red, Orange, Yellow, Green , Blue) and bind 5 checkboxes in the form to each of these fields? This option requires zero coding.

Adas – Much appreciated on the note. You are correct, I think this is the alternative I’ll have to go with. I’m trying to push myself to code where possible, since I know that it will help me in the long run. For now, I’ll stick with the non-code alternative I suppose.

Thanks!

Re-visiting this post. I’m getting an Error that “forEach”. Isn’t this just part of the API? Why would it be undefined???

let j = {};

$w('Checkbox').forEach(function(c){
	j[c.value] = c.checked; 

});  	

console.log(j); 

Hi David!
This seems like an issue in the code inspection, we’ll have a look, thanks for letting us know.

Although your code should still work (inspection won’t prevent the code from running), consider using [Array.from()](Array.from() - JavaScript | MDN) method of Array prototype:

Array.from($w('Checkbox')).forEach(...)

This will make everything work as expected :slight_smile:

Hope this helps,

Liran.

OK –

I have an array which lists which values have been “checked”. How can I take the true values from this array and add them into a textbox??

Simply, I need to set my textbox value to “Red, Yellow, Blue”

//Sample Array
//{"Red":true,"Orange":false,"Yellow":true,"Green":false,"Blue":true}

Hi David,
This actually looks like an Object (a map of keys and values), which is different than Array.
Still, should be easily done by iterating the object, see examples here .

Liran.