Checkbox

2 snippets across 2 stacks — HTML & CSS, React

HCHTML & CSS

Checkboxes & Radio Buttons

HC · Forms
syntax
<input type="checkbox" name="field" value="val">
<input type="radio" name="group" value="val">
example
<fieldset>
  <legend>Notification Preferences</legend>
  <label><input type="checkbox" name="notify" value="email"> Email</label>
  <label><input type="checkbox" name="notify" value="sms"> SMS</label>
</fieldset>

<fieldset>
  <legend>Priority</legend>
  <label><input type="radio" name="priority" value="low"> Low</label>
  <label><input type="radio" name="priority" value="high"> High</label>
</fieldset>

Note Radio buttons with the same name attribute form an exclusive group where only one can be selected. Checkboxes allow multiple selections. Wrap each in a label for a clickable hit area.

REReact

Select, Checkbox & Radio

RE · Forms
syntax
// Select
<select value={state} onChange={handler}>...
// Checkbox
<input type="checkbox" checked={state} onChange={handler} />
// Radio
<input type="radio" value="opt" checked={state === 'opt'} onChange={handler} />
example
function PreferencesForm() {
  const [color, setColor] = useState('blue');
  const [newsletter, setNewsletter] = useState(false);
  const [plan, setPlan] = useState('free');

  return (
    <form>
      {/* Select */}
      <label>Favorite Color</label>
      <select value={color} onChange={e => setColor(e.target.value)}>
        <option value="blue">Blue</option>
        <option value="green">Green</option>
        <option value="red">Red</option>
      </select>

      {/* Checkbox */}
      <label>
        <input
          type="checkbox"
          checked={newsletter}
          onChange={e => setNewsletter(e.target.checked)}
        />
        Subscribe to newsletter
      </label>

      {/* Radio */}
      {['free', 'pro', 'enterprise'].map(option => (
        <label key={option}>
          <input
            type="radio"
            name="plan"
            value={option}
            checked={plan === option}
            onChange={e => setPlan(e.target.value)}
          />
          {option}
        </label>
      ))}
    </form>
  );
}

Note For checkboxes, read e.target.checked (boolean), not e.target.value. For selects, value goes on the <select> element, not on individual <option> elements. Radio buttons in the same group share the same name attribute.