先看代碼:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>demo</title> <style> input[type="submit"]{ width: 120px; height: 40px; border: 0; background-color: antiquewhite; } input[type="submit"]:hover{ background-color: beige; } </style> </head> <body> <form action="#" method="post"> <label><input type="radio" required />高中</label> <label><input type="radio" required />大專</label> <label><input type="radio" required />本科</label> <label><input type="radio" required />碩士研究生</label> <label><input type="radio" required />博士及以上</label> <br /> <input type="submit" value="提交" /> </form> </body> </html>
提交數據時並沒有進行非空驗證。
正確代碼為:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>demo</title> <style> input[type="submit"]{ width: 120px; height: 40px; border: 0; background-color: antiquewhite; } input[type="submit"]:hover{ background-color: beige; } </style> </head> <body> <form action="#" method="post"> <label><input type="radio" name="q1" required />高中</label> <label><input type="radio" name="q1" required />大專</label> <label><input type="radio" name="q1" required />本科</label> <label><input type="radio" name="q1" required />碩士研究生</label> <label><input type="radio" name="q1" required />博士及以上</label> <br /> <input type="submit" value="提交" /> </form> </body> </html>
原因:
單項選擇的實現是通過對多個單選按鈕設置同樣的name屬性值和不同的選項值。例如,使用兩個單選按鈕,設置這兩個控件的name值為sex,選項值一個為女,一個為男,從而實現從性別中選擇一個的單選功能。
單選按鈕有一個重要的屬性checked,用來設置或返回單選按鈕的狀態。一組name值相同的單選按鈕中,如果其中一個按鈕的checked屬性被設置為true,則其他按鈕的checked屬性值就默認為false。