【HTML】ラジオボタンの作成と制御
- ラジオボタンの基本的な使い方
- ラジオボタンのグループ化
- ラベルの関連付け
- デフォルトの選択状態を設定する
- ラジオボタンの無効化
- フィールドセットを使用する
- CSSを使ったカスタマイズ
- JavaScriptを使ったラジオボタンの制御
ラジオボタンの基本的な使い方
ラジオボタンは、ユーザーが複数の選択肢の中から1つだけを選べるようにする入力要素です。
<input type="radio" name="example" value="option1"> 選択肢1
<input type="radio" name="example" value="option2"> 選択肢2
<input type="radio" name="example" value="option3"> 選択肢3
ラジオボタンのグループ化
ラジオボタンをグループ化するには、name
属性を同じにします。
<input type="radio" name="fruit" value="apple"> りんご
<input type="radio" name="fruit" value="banana"> バナナ
<input type="radio" name="fruit" value="grape"> ぶどう
ラベルの関連付け
ラベルを使用すると、ラジオボタンのクリック範囲を広げることができます。
<label><input type="radio" name="drink" value="tea"> お茶</label>
<label><input type="radio" name="drink" value="coffee"> コーヒー</label>
<label><input type="radio" name="drink" value="juice"> ジュース</label>
また、for
属性を使ってラジオボタンと明示的に関連付けることもできます。
<input type="radio" id="male" name="gender" value="male">
<label for="male">男性</label>
<input type="radio" id="female" name="gender" value="female">
<label for="female">女性</label>
デフォルトの選択状態を設定する
ラジオボタンの初期状態で選択させたい場合は、checked
属性を追加します。
<input type="radio" name="food" value="rice" checked> ご飯
<input type="radio" name="food" value="bread"> パン
<input type="radio" name="food" value="noodle"> 麺類
ラジオボタンの無効化
ラジオボタンを選択できないようにするには、disabled
属性を使います。
<input type="radio" name="mode" value="day"> 昼モード
<input type="radio" name="mode" value="night" disabled> 夜モード(無効)
フィールドセットを使用する
複数のラジオボタンをfieldset
で囲むと、より視覚的に分かりやすくなります。
<fieldset>
<legend>好きな動物を選んでください</legend>
<input type="radio" name="animal" value="dog"> 犬
<input type="radio" name="animal" value="cat"> 猫
<input type="radio" name="animal" value="bird"> 鳥
</fieldset>
CSSを使ったカスタマイズ
デフォルトのラジオボタンはデザインを変更しにくいですが、CSSを使えばカスタマイズできます。
<style>
input[type="radio"] {
display: none;
}
input[type="radio"] + label {
cursor: pointer;
padding: 5px 10px;
border: 1px solid #ccc;
border-radius: 5px;
}
input[type="radio"]:checked + label {
background-color: #007bff;
color: white;
}
</style>
<input type="radio" id="option1" name="custom" value="1">
<label for="option1">選択肢1</label>
<input type="radio" id="option2" name="custom" value="2">
<label for="option2">選択肢2</label>
JavaScriptを使ったラジオボタンの制御
JavaScriptを使って、ラジオボタンの選択状態を変更できます。
<script>
function selectRadio(value) {
document.querySelector('input[name="color"][value="' + value + '"]').checked = true;
}
</script>
<input type="radio" name="color" value="red"> 赤
<input type="radio" name="color" value="blue"> 青
<input type="radio" name="color" value="green"> 緑
<button onclick="selectRadio('blue')">青を選択</button>