2010-08-11 152 views
0

我如何讓用戶只檢查其中一個複選框..除了禁用選擇框上的複選框,還有其他方法嗎?限制選擇複選框

<td width="25%"><input type="checkbox" name="choice" value="Good" />Good</td> 
<td width="25%"><input type="checkbox" name="choice" value="Average" />Average</td> 
<td width="25%"><input type="checkbox" name="choice" value="Sucks" />Sucks</td> 
<td width="25%"><input type="checkbox" name="choice" value="Fascinating" />Fascinating</td> 

如果它在JavaScript,請簡單理解..

+2

怎麼會「吸」其次是「迷人的」 ........ – kennytm 2010-08-11 09:54:37

+1

是,使用單選按鈕 - 這就是他們什麼(http://www.w3schools.com /html/tryit.asp?filename=tryhtml_radio) – 2010-08-11 09:54:55

回答

5

你正在尋找一個radio button group

<td width="25%"><input type="radio" name="choice" value="Good" />Good</td> 
<td width="25%"><input type="radio" name="choice" value="Average" />Average</td> 
<td width="25%"><input type="radio" name="choice" value="Sucks" />Sucks</td> 
<td width="25%"><input type="radio" name="choice" value="Fascinating" />Fascinating</td> 
+0

+1,darnit!打敗我3秒:-P下面是OP的一個例子:http://jsfiddle.net/avXs3/ – 2010-08-11 09:57:14

+0

@Andy我打算回覆說我的速度更快,因爲我實際上有*手*鍵入,但是然後我看着你的用戶名。很高興看到你有你的身體回來! :) – 2010-08-11 09:58:31

+0

@皮卡:什麼,這個老東西?是的,這不是我的,我只是借了它;) – 2010-08-11 10:01:48

0

如果用戶只能同時選擇其中的一個,你應該使用<input type="radio">而不是checkbox

如果必須使用checkbox,嘗試(example):

var choices = document.getElementsByName('choice'); 

for (var i = choices.length-1; i >= 0; -- i) { 
    choices[i].onclick = function() { 
    for (var j = choices.length-1; j >= 0; -- j) { 
     if (choices[j] != this) 
     choices[j].checked = false; 
    } 
    } 
}