HTMLでのラジオボタンについて
概要
ラジオボタンとは、ユーザがクリックして押された状態と押されていない状態を切り替えることが出来るボタンである。

以下にコード例を示す。
なお、ラジオボタンにはtextContentがないためlabelタグで文字を表示している。
<input type="radio" name="option" id="option1" value="Option 1" checked>
<label for="option1">Option 1</label>typeプロパティでradioを指定する。
nameプロパティでラジオボタンのグループを設定する。
このグループ内のラジオボタンは、押されているボタンが1つに制限される。
valueプロパティで選択されたボタンの値を決める。
checkedプロパティは最初からチェックがされているかを指定する。
ボタン検知
ラジオボタンのボタンの検知はaddEventListenerのchangeで検知する。
const radioButtons = document.getElementById('option1');
radioButton.addEventListener('change', function() {
if (radioButton.checked) {
console.log(`選択されたラジオボタンの値: ${radioButton.value}`);
}
}); 複数のボタンを一度に定義
const radioButtons = document.querySelectorAll('input[type="radio"]'); radioButtons.forEach(function(radioButton) {
radioButton.addEventListener('change', function() {
if (radioButton.checked) {
console.log(`選択されたラジオボタンの値: ${radioButton.value}`);
}
});
});labelとの紐づけ
labelにはfor、radioButtonにはid、それぞれを同じにするとlabelとradioButtonが紐づけされる。
label.setAttribute("for", timeTableDayTypeArg + radioID);