4
$\begingroup$

Is there an easy way to limit the number of selections in a CheckboxBar such that at any time you can choose only two options. I tried to use the "Enabled" option, but that grays out the whole checkboxBar. How can access individual Checkbox in CheckboxBar (so that, I can disable only those Checkboxes that are not selected) ?

Manipulate[NumSelec, {NumSelec, {1, 2, 3, 4}, ControlType -> CheckboxBar,  Enabled -> If[Length[NumSelec] >= 2, False, True]}]
$\endgroup$
7
$\begingroup$

Use the second argument to Dynamic. Example:

DynamicModule[{NumSelec = {}},
 Column[{
   CheckboxBar[
    Dynamic[NumSelec, (If[Length[#] > 2, NumSelec = #[[-2 ;;]], 
        NumSelec = #]) &], {1, 2, 3, 4}],
   Dynamic[NumSelec]
   }]
 ]

enter image description here

$\endgroup$
1
$\begingroup$

This is one way using DynamicModule

 DynamicModule[{NumSelec1 = {}, NumSelec2 = {}, NumSelec3 = {}, false},
 Column[{
   Dynamic@
    Row[{CheckboxBar[Dynamic[NumSelec1], {1}, 
       Enabled -> (NumSelec1 =!= {} || false)], 
      CheckboxBar[Dynamic[NumSelec2], {2}, 
       Enabled -> (NumSelec2 =!= {} || false)], 
      CheckboxBar[Dynamic[NumSelec3], {3}, 
       Enabled -> (NumSelec3 =!= {} || false)]}],
   Dynamic[false = (Length[join] < 2); 
    join = Join[NumSelec1, NumSelec2, NumSelec3]]
   }]
 ]
$\endgroup$
1
$\begingroup$

Here's a way using a function to rewrite the dynamic value when length of 2 is exceeded.

Manipulate[
 NumSelec = limit[NumSelec, 2], {NumSelec, {1, 2, 3, 4}, ControlType -> CheckboxBar}, 
 Initialization :> (
  limit[x_, num_] := If[ListQ[x], If[Length[x] > num, x[[-num ;;]], x], x])
]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.