setChecked

Category:UI Controls

Sets the state of a checkbox or radioButton.

setChecked() is used by your app to mark or unmark a checkbox or radio button by using the element ID. Check boxes are used when the user is asked to check a box if they agree with something, like an app privacy statement. Radio buttons are used when the user is asked to choose one item from a predefined group of options.

Examples

Example: Tell Me My Favorite Color

Randomly click a radio button in a group.

// Randomly click a radio button in a group.
radioButton("Red", false,"ColorGroup");
textLabel("RedLabel","Red","Red");
radioButton("Blue", false,"ColorGroup");
textLabel("BlueLabel","Blue","Blue");
radioButton("Green", false,"ColorGroup");
textLabel("GreenLabel","Green","Green");
radioButton("Orange", false,"ColorGroup");
textLabel("OrangeLabel","Orange","Orange");

button("favorite","What's my favorite color?");
onEvent("favorite","click", function() {
    var radioIDs = ["Red","Blue","Green","Orange"];
    setChecked(radioIDs[randomNumber(0,radioIDs.length-1)], true);
});

// Check a checkbox if the user clicks anywhere on the top half of the screen, otherwise uncheck it.
checkbox("agreeBox", false);
textLabel("agreeLabel","I agree to the above privacy statement.","agreeBox");

onEvent("screen1","click", function(event) {
  if (event.offsetY<=225) {
    setChecked("agreeBox", true);
  }
  else{
    setChecked("agreeBox", false);
  }
});

Syntax

setChecked(id, checked)

Parameters

Name Type Required? Description
checked boolean Whether the screen element is initially checked.
id string The unique identifier for the screen element. Must begin with a letter, contain no spaces, and may contain letters, digits, - and _. |

Returns

No return value. Modifies screen only.

Tips

  • A checkbox or radio button can also be created in design mode.
  • Only one button in a group can be checked at a time. Any radio buttons without a group specified will be in the same default, unnamed group.

Found a bug in the documentation? Let us know at documentation@code.org