not good but great

プログラミング、アート、映画・本の感想について書きます。

項目名をクリックしてradioボタンをcheckedにする方法

inputタグに閉じタグはいらない

書いている途中に迷って調べてみた。

br, img, hrにも閉じタグはいらない
Webデザインリリック | Web Design Lyric

labelタグにforを設定する

<input id="sample" type="radio"><label for="sample">Hello World!</label>

labelタグを加えて、属性forの値をid名にすれば、radioの丸だけではなく項目名を押してもcheckedになる。

<label><input id="sample" type="radio">Hello World!</label>

このようにforを使わないやり方もあるが、IE5,6では動かない。

<LABEL>-HTMLタグリファレンス
ラジオボタンにはlabelタグのforが便利 - モジログ

name属性を同じにして一つだけ選択できるようにする

<input id="sample" type="radio"><label for="sample">Hello</label>
<input id="sample2" type="radio"><label for="sample2">GoodBye</label>

上のようにやると、ラジオボタンを複数選択できるようになってしまう。加えて同じラジオボタンを押してtrue,falseの切り替えもできない。

<input id="sample" type="radio" name="greeting"><label for="sample">Hello</label>
<input id="sample2" type="radio" name="greeting"><label for="sample2">GoodBye</label>

一つだけ選択できて、true,falseの切り替えができるようにするためには、name属性の名前を同じにすればよい。

ミスティーネット・HTML講座・入力フォームを作成する
<input type="radio">要素(ラヂヲボタン) - HTML リファレンス

最初から一つ選択しておく方法

<input id="sample" type="radio" name="greeting" checked><label for="sample">Hello</label>
<input id="sample2" type="radio" name="greeting"><label for="sample2">GoodBye</label>

選択しておきたい要素のinputタグ内に「checked」を記述すればOK.