2

This question is related to the following

Interactively select a row/column of a Grid

I’d like to present information in a grid where in the user can choose from the entries in the table. As shown in the figure:

Select rows in a table

Here’s some sample code:

tableHeaders = {"A", "B", "C", "D"};
data = Table[10 i + j, {i, 3}, {j, 3}];
checkBoxes = Table[Checkbox[True], {i, 3}];
table = Transpose@Insert[Transpose@data, checkBoxes, 1];


Grid[Insert[table, tableHeaders, 1]
 , Alignment -> {Left, Baseline}
 , Spacings -> {1.4, 1.3}
 , FrameStyle -> LightGray
 , Frame -> True
 , Background -> {None, {Lighter@Lighter@LightBlue, None}}
 , Dividers -> {{True, True}, {True, True}}
]

I tried to get define variables table/checkBoxes as a Dynamic but Mathematica throws up errors.

Question: How do I modify the code so that I can get a list of rows that are checked in the grid.

Pam
  • 1,867
  • 11
  • 24

3 Answers3

3

I was able to find a simple solution… turns out I was using Dynamic in the wrong context… This code works

tableHeaders = {"A", "B", "C", "D"};
data = Table[10 i + j, {i, 3}, {j, 3}];
checkBoxes = Checkbox /@ {Dynamic[x], Dynamic[y], Dynamic[z]}


table = Insert [Transpose@Insert[Transpose@data, checkBoxes, 1], 
tableHeaders, 1];

grid = Dynamic@Grid[table
 , Alignment -> {Left, Baseline}
 , Spacings -> {1.4, 1.3}
 , FrameStyle -> LightGray
 , Frame -> True
 , Background -> {None, {Lighter@Lighter@LightBlue, None}}
 , Dividers -> {{True, True}, {True, True}}
 ]
Pam
  • 1,867
  • 11
  • 24
1

If you want to use an array to indicate the selected rows, you can make these changes:

selected = ConstantArray[False, Length@data];
checkBoxes = Table[With[{i = i}, Checkbox@Dynamic@selected[[i]]], {i, 3}];

Then to get the currently selected rows, execute the following:

Pick[data, selected]
(*  {{11, 12, 13}, {31, 32, 33}}  *)
Michael E2
  • 235,386
  • 17
  • 334
  • 747
  • Thank you. I picked Andre’s answer due to the elegance of his myCheckBox function which maintains the order in which checkboxes were checked and unchecked. – Pam Aug 10 '18 at 12:17
1

Instead of using 3 variables x,y,z the code below uses a unique variable choices which is a List

tableHeaders = {"A", "B", "C", "D"};
data = Table[10 i + j, {i, 3}, {j, 3}];

choices={};
checkBoxes = Table[myCheckbox[choices,i], {i, 3}];
table = Transpose@Insert[Transpose@data, checkBoxes, 1];


Grid[Insert[table, tableHeaders, 1]
 , Alignment -> {Left, Baseline}
 , Spacings -> {1.4, 1.3}
 , FrameStyle -> LightGray
 , Frame -> True
 , Background -> {None, {Lighter@Lighter@LightBlue, None}}
 , Dividers -> {{True, True}, {True, True}}
]

Dynamic[choices]

enter image description here

Note : One can find on Mathematica Stack Exchange three other answers where I have used myCheckbox.

andre314
  • 18,474
  • 1
  • 36
  • 69