Grouped Checkboxes

by osban

Level: beginner • Mithril.js Version: latest

This example shows a form with multiple checkboxes that are grouped so that only one checkbox per group can be selected. So, the behavior of the checkboxes is like radio buttons. The example shows also, how to use simple helper functions to make Mithril.js code simpler.

Live Example

Dependencies

Type Name URL
scriptmithril@latesthttps://unpkg.com/mithril@latest

JavaScript

const list = [
  [
    {label: "1", groupId: 0},
    {label: "2", groupId: 0},
    {label: "5", groupId: 0}
  ],
  [
    {label: "4", groupId: 1},
    {label: "3", groupId: 1}
  ],
  [
    {label: "6", groupId: 2},
    {label: "7", groupId: 2}
  ]
]

const model = []

const checkboxView = ({groupId, label}) => {
  const checked = model[groupId] === label
  return m('label',
    m('input[type=checkbox]', {
      checked,
      onchange: () => model[groupId] = checked ? '' : label,
    }),
    label
  )
}

const groupView = attrs => m('div', attrs.map(checkboxView))

const app = {
  view: () => [
    m('h1', 'Checkbox Groups'),
    list.map(groupView),
    m('p', model.filter(x => x).join(',')),
  ]
}

m.mount(document.body, app)

CSS

label { display: inline-block }

As a prerequisite for this snippet, the latest version of Mithril.js framework is required. Beginners should have no problems following this example, that simply shows some basic recipies.

In this code sample Mithril.js' m.mount API method is use, besides the basic hyperscript function m().

The example was written by osban, last edits were made on 24 October 2021. The author has contributed some more snippets. Click here to see them all.

Contribute

Did you note a typo or something else? So let me know by opening an issue. Or much better: just fork the repository on GitHub, push your commits and send a pull request. Ready to start your work? Then click on the edit link below. Thanks in advance!

See more code examples  •  Edit this example on GitHub