DOMとフォーム:チェックボックス・ラジオボタンの状態取得

基本プロパティ

  • checked(boolean)
    現在の選択状態。true/false を返します。

  • value(string)
    送信時に送られる値。value 属性を省略すると既定で "on" になります。

  • defaultChecked(boolean)
    HTML上(初期描画時)の既定状態。form.reset() で戻る先。

  • indeterminate(checkboxのみ, boolean)
    3 状態 UI(半チェック)用のプロパティ専用フラグ。属性は存在しません。送信値にも影響しません(見た目だけ)。

取得時は 真偽を知りたい→checked、送信値が欲しい→value と覚えてください。


単体取得(1つの要素)

html
<input id="news" type="checkbox" name="subscribe" value="news"> <input id="color-red" type="radio" name="color" value="red">
js
const cb = document.getElementById('news'); // HTMLInputElement const isChecked = cb.checked; // true / false const val = cb.value; // "news"(value未指定なら "on") const r = document.getElementById('color-red'); const selected = r.checked; // true / false

まとめて取得:CSSセレクタ :checked

チェックボックス(複数選択)

html
<label><input type="checkbox" name="fruits" value="apple">Apple</label> <label><input type="checkbox" name="fruits" value="banana">Banana</label> <label><input type="checkbox" name="fruits" value="cherry">Cherry</label>
js
// 現在チェックされている要素群 const checkedBoxes = document.querySelectorAll('input[type="checkbox"][name="fruits"]:checked'); // 値の配列を得る const values = Array.from(checkedBoxes, el => el.value); // ["apple", "cherry"] など

ラジオボタン(単一選択)

html
<label><input type="radio" name="color" value="red">Red</label> <label><input type="radio" name="color" value="green">Green</label> <label><input type="radio" name="color" value="blue">Blue</label>
js
const selectedRadio = document.querySelector('input[type="radio"][name="color"]:checked'); const value = selectedRadio ? selectedRadio.value : null; // 未選択なら null

form.elements を使う(名前で参照)

フォームに紐づけられた要素は HTMLFormElement#elements から名前で参照できます。

html
<form id="f1"> <label><input type="checkbox" name="fruits" value="apple">Apple</label> <label><input type="checkbox" name="fruits" value="banana">Banana</label> <label><input type="radio" name="color" value="red">Red</label> <label><input type="radio" name="color" value="blue">Blue</label> </form>
js
const form = document.getElementById('f1'); // 同じ name を持つ複数のチェックボックスは RadioNodeList 風のコレクション const fruits = form.elements.namedItem('fruits'); // HTMLInputElement | RadioNodeList const fruitValues = Array.from(fruits).filter(el => el.checked).map(el => el.value); // ラジオは選択中の value を直接取得できる(未選択は "") const color = form.elements.namedItem('color'); // RadioNodeList const colorValue = color.value || null;

送信時の収集は FormData が簡単

  • 同名チェックボックスは 複数値になるので getAll を使用。

  • ラジオは 単一値get

js
const fd = new FormData(form); const selectedFruits = fd.getAll('fruits'); // ["apple", "banana"] const selectedColor = fd.get('color'); // "red" など(未選択は null 相当)

FormData無効化された要素(disabled)は含めません。必要なら個別に .checked を参照してください。


変更検知(イベント)

  • change:チェック状態が確定した時点で発火(チェックボックス/ラジオはクリックやキーボード操作直後)。

  • input:近年はほぼ同様に発火しますが、change の方が互換実績が長いです。

イベントデリゲーション例(親に1つだけリスナを付ける):

js
document.addEventListener('change', (e) => { const t = e.target; if (!(t instanceof HTMLInputElement)) return; if (t.type === 'checkbox') { console.log('checkbox', t.name, t.value, t.checked); } else if (t.type === 'radio') { if (t.checked) { console.log('radio group', t.name, 'value', t.value); } } });

indeterminate(三状態チェックボックス)

ツリー選択や「全選択」UIで便利です。見た目のみで送信値は変化しません。

js
const master = document.querySelector('#select-all'); master.indeterminate = true; // 半チェック表示

クリックするとブラウザが自動で indeterminatefalse に戻す点に注意し、必要なら再設定します。


よくある落とし穴

  1. value を省略していると送信時は "on"。値で識別したいなら value を明示。

  2. checked 属性とプロパティの混同

    • 属性:初期状態(HTML)

    • プロパティ:現在状態(JS)。動的に変わるのはプロパティ。

  3. 未選択のラジオquerySelector('…:checked')null。必ず null チェックを行う。

  4. disabled 要素は FormData に含まれない。状態確認は .checked で。

  5. form.reset() は現在状態を初期値(defaultChecked)に戻す。直近の選択を消したいだけなら個別に .checked=false を設定。


ミニ実装例:選択の表示と送信データ整形

html
<form id="prefs"> <fieldset> <legend>通知方式</legend> <label><input type="checkbox" name="notify" value="email">Email</label> <label><input type="checkbox" name="notify" value="sms">SMS</label> <label><input type="checkbox" name="notify" value="push">Push</label> </fieldset> <fieldset> <legend>テーマ色</legend> <label><input type="radio" name="theme" value="light">Light</label> <label><input type="radio" name="theme" value="dark">Dark</label> </fieldset> <button type="button" id="show">状態確認</button> </form> <pre id="out"></pre>
js
const form = document.getElementById('prefs'); const out = document.getElementById('out'); document.getElementById('show').addEventListener('click', () => { // 1) セレクタで取得 const notifies = Array.from(form.querySelectorAll('input[name="notify"]:checked')) .map(el => el.value); const themeEl = form.querySelector('input[name="theme"]:checked'); const theme = themeEl ? themeEl.value : null; // 2) FormDataでも取得 const fd = new FormData(form); const fdNotifies = fd.getAll('notify'); const fdTheme = fd.get('theme'); out.textContent = JSON.stringify({ notifies, theme, fdNotifies, fdTheme }, null, 2); });

テストや型付け(TypeScriptヒント)

ts
const el = document.querySelector<HTMLInputElement>('input[name="x"]'); if (el?.type === 'checkbox' && el.checked) { /* … */ }
  • querySelector<HTMLInputElement> のジェネリクス指定で型安全に扱えます。


まとめ

  • 状態の真偽は checked、送信値は value

  • 複数チェックは :checked + querySelectorAll、ラジオは 単一の :checked を探す。

  • 送信データ整形は FormData#getAll/get が簡潔。

  • 初期状態・現在状態・見た目だけの三状態(defaultChecked / checked / indeterminate)を区別することが正確な実装の鍵です。

ChatGPT5 生成日:2025/09/11