單選按鈕只能從一組選項中選出一項,選項之間彼此互斥。
語法:
<input type="radio" name="單選按鈕所在的組名" value="單選按鈕的取值"/>
說明:name 與 value 都是 radio 的必填屬性,一定要寫。
舉例:
<!DOCTYPE html> <html xmlns="https://www.w3.org/1999/xhtml"> <head> <title></title> </head> <body> <form name="form1" method="post" action="index.html"> 性別: <input type="radio" name="Question1" value="boy"/>男 <input type="radio" name="Question1" value="girl"/>女 </form> </body> </html>
仔看上面的代碼,兩個選項的 name 值是一樣的。如果把它們改成不同的名字會怎樣?我們把第二個改成 Question2:
結果是——同一題的兩個選項居然可以同時選中,完全不符合預期。
所以規則很明確:同一個問題的所有選項,必須共用同一個 name 值,瀏覽器才會把它們視為同一組。
看一個多題的例子就更清楚了:
<!DOCTYPE html> <html xmlns="https://www.w3.org/1999/xhtml"> <head> <title></title> </head> <body> <form name="form1" method="post" action="index.html"> 性別: <input type="radio" name="Question1" value="boy"/>男 <input type="radio" name="Question1" value="girl"/>女<br/> 你是: <input type="radio" name="Question2" value="90"/>90後 <input type="radio" name="Question2" value="00"/>00後 <input type="radio" name="Question2" value="else"/>其他 </form> </body> </html>
兩組各自獨立,選了性別不影響世代那一題,這就是 name 分組的效果。
外觀上完全看不出差別。加 value 的目的是為了把資料往伺服器端送,屬於後端技術的範疇。所以請先照規矩寫,養成良好的代碼習慣;有些設計對初學者來說確實還不到能理解的時機。
另外老實說一句:表單這一章真正要精通並不容易,不是記幾個標籤就完事,後續還有不少內容要學。