
Svelteのvalueは文字列と数値を判別
Svelteでフォームを作成していたら1つ目のcheckboxにcheckedが入っていないことがあった。
コードであらわすと以下のような感じです。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | < script > let scoops = 1 </ script > < h2 >最初のcheckboxが選択されないサンプル</ h2 > < form > < label > < input type = radio bind:group={scoops} name = "scoops" value = "1" > One </ label > < label > < input type = radio bind:group={scoops} name = "scoops" value = "2" > Two </ label > < label > < input type = radio bind:group={scoops} name = "scoops" value = "3" > Three </ label > </ form > < p >{scoops}を選択</ p > |
ちなみにchecked属性を追加しても value="1" が選択状態にならないです。
1 | < input type = radio bind:group={scoops} name = "scoops" value = "1" checked> |
調べたところSvelteではvalueの文字列と数値の書き方がわけられているので、scoopsが文字列の場合は「value="1"」だが、数値の場合は「value={1}」と書かないと正しく動作しない仕様だった。
特にビルドしてもエラーにならず、選択不可になるわけではないので見落としやすい仕様だと思いました。
正しいコードは以下の通りです。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | < script > let scoops = 1 </ script > < h2 >最初のcheckboxが選択されないサンプル</ h2 > < form > < label > < input type = radio bind:group={scoops} name = "scoops" value={1}> One </ label > < label > < input type = radio bind:group={scoops} name = "scoops" value={2}> Two </ label > < label > < input type = radio bind:group={scoops} name = "scoops" value={3}> Three </ label > </ form > < p >{scoops}を選択</ p > |