Checkbox
A control that allows the user to toggle between checked and not checked.
Usage
Example
div(class: 'flex items-center space-x-3') do Checkbox(id: 'terms') label(for: 'terms', class: 'text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70') { "Accept terms and conditions" } end
Copied!
Copy failed!
Checked
You agree to our Terms of Service and Privacy Policy.
div(class: "items-top flex space-x-3") do Checkbox(id: 'terms1', checked: true) div(class: "grid gap-1.5 leading-none") do label( for: "terms1", class: "text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70" ) { " Accept terms and conditions " } p(class: "text-sm text-muted-foreground") { " You agree to our Terms of Service and Privacy Policy." } end end
Copied!
Copy failed!
Installation
Using RubyUI CLI
Run the install command
rails g ruby_ui:component Checkbox
Copied!
Copy failed!
Manual installation
1
Add RubyUI::Checkbox
to app/components/ruby_ui/checkbox.rb
# frozen_string_literal: true module RubyUI class Checkbox < Base def view_template input(**attrs) end private def default_attrs { type: "checkbox", data: { ruby_ui__form_field_target: "input", ruby_ui__checkbox_group_target: "checkbox", action: "change->ruby-ui--checkbox-group#onChange change->ruby-ui--form-field#onInput invalid->ruby-ui--form-field#onInvalid" }, class: "peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 accent-primary" } end end end
Copied!
Copy failed!
2
Add RubyUI::CheckboxGroup
to app/components/ruby_ui/checkbox/checkbox_group.rb
# frozen_string_literal: true module RubyUI class CheckboxGroup < Base def view_template(&) div(**attrs, &) end private def default_attrs { role: "group", data: { controller: "ruby-ui--checkbox-group" } } end end end
Copied!
Copy failed!
3
Add checkbox_group_controller.js
to app/javascript/controllers/ruby_ui/checkbox_group_controller.js
import { Controller } from "@hotwired/stimulus"; export default class extends Controller { static targets = ["checkbox"]; connect() { this.#handleRequired(); } onChange() { this.#handleRequired(); } #handleRequired() { if (!this.element.hasAttribute("data-required")) return; const checked = this.checkboxTargets.some(({ checked }) => checked); this.checkboxTargets.forEach((checkbox) => (checkbox.required = !checked)); } }
Copied!
Copy failed!
4
Update the Stimulus controllers manifest file
Importmap!
You don't need to run this command if you are using Importmap
rake stimulus:manifest:update
Copied!
Copy failed!
Components
Component | Built using | Source |
---|---|---|
Checkbox | Phlex | |
CheckboxGroup | Phlex | |
CheckboxGroupController | Stimulus JS |