我有一個表單,我想要得到哪個複選框在普通JS中被選中並且返回它的值。我用單選按鈕來獲取它,但沒有用複選框,只是不能弄清楚它應該如何調用它與單選按鈕相同,它會返回下面的空字符串代碼。document.forms複選框的值
例如用單選按鈕:
/*html*/
<input type="radio" name="q5" value="a" id="q5a">a. test1<br>
<input type="radio" name="q5" value="b" id="q5b">b. test2<br>
/*js, gets the value which is selected either a or b as per html*/
var q5 = document.forms["quizForm"]["q5"].value;
現在我嘗試這與複選框:
/*html*/
<input type="checkbox" name="q6" value="c" id="q6c">c. test1<br>
<input type="checkbox" name="q6" value="d" id="q6d">d. test2<br>
/*js returns an empty string "" when either checked or both*/
var q6 = document.forms["quizForm"]["q6"].value;
使用布爾屬性'.checked'而不是'.value' – Seblor
它給出undefined back – Zygimantas