0
$\begingroup$

I am programmatically generating some cells that have a checkbox along with some text. The following code creates a button which when clicked, creates such cells.

var = InputNotebook[];
Button["InsertCell",
    NotebookWrite[var, 
      Cell[BoxData[ToBoxes[Dynamic[If[sel, "Selected", "Not selected"]]]], "Section"]];
      NotebookWrite[var, Cell[BoxData[ToBoxes[Checkbox[Dynamic[sel]]]], "Subsection"]
    ]
]

When the checkbox is selected, the text changes to "Selected" and when the checkbox is unchecked, it shows "Not selected".

The problem is that when I create multiple cells by clicking the button and select a checkbox from any one cell, the change is reflected in all the cells. Is there a way to localize this change? And could this be extended to changing the styles of the particular cell where the checkbox is checked? For example, when the checkbox in a particular cell is checked, I want its background color to become LightGreen.

Any help is very much appreciated. Thanks.

P.S: I am trying to create a small Todolist application and therefore I require this feature.

$\endgroup$

1 Answer 1

1
$\begingroup$

I would use With to inject unique variables into the Dynamic objects. Try:

var=InputNotebook[];
Button[
    "InsertCell",
    With[{sel=Unique[]},
        NotebookWrite[
            var,
            Cell[
                BoxData[ToBoxes[Dynamic[If[sel,"Selected","Not selected"]]]],
                "Section"
            ]
        ];
        NotebookWrite[
            var,
            Cell[
                BoxData[ToBoxes[Checkbox[Dynamic[sel]]]],
                "Subsection",
                Background->Dynamic[If[sel,LightGreen,None]]
            ]
        ]
    ]
]
$\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.