2011-12-12 84 views
0

我正在嘗試這樣做。JavaScript啓用禁用單選按鈕,並一次只選擇一個

我有3個單選按鈕,

  1. 如果在一個電臺點擊它的設置,下一次我點擊它。它應該 未經檢查/休息。

我想在沒有jquery的標準javascript中做,因爲目前還不能。

這是我的代碼到目前爲止。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
    <title> New Document </title> 
    <meta name="Author" content=""> 
    <meta name="Keywords" content=""> 
    <meta name="Description" content=""> 

    <script type="text/javascript"> 

    function toggle(radioBtn) 
    { 
    if(radioBtn.checked) 
    { 
     radioBtn.checked = false; 
    } 
    else 
    { 
     radioBtn.checked = true; 
    } 


    // only select one at a time. 

    } 

    </script> 
</head> 

<body> 
<form id="myForm" name="myForm"> 
    <input type="radio" name="radioBtn" id="radioBtn1" value="A" onClick="toggle(this);" /> 
<input type="radio" name="radioBtn" id="radioBtn1" value="B" onClick="toggle(this);"/> 
<input type="radio" name="radioBtn" id="radioBtn1" value="C" onClick="toggle(this);"/> 
</form> 
</body> 
</html> 

請大家幫忙。您的幫助將不勝感激。 感謝

+1

共享相同「名稱」屬性的單選按鈕將由瀏覽器管理,因此無法設置多個按鈕。換句話說,我不明白你爲什麼需要代碼來做到這一點。 – Pointy

+0

@Pointy,謝謝。你現在正想要另一部分。切換單選按鈕。我怎樣才能做到這一點。 – Nomad

+0

你不能設置多個單選按鈕。您必須使用複選框。 –

回答

9

你可能只是做一些簡單和直接的內聯,就像這樣:

<input type="radio" name="radioBtn" id="radioBtn1" value="A" onMouseDown="this.__chk = this.checked" onClick="if (this.__chk) this.checked = false" /> 
<input type="radio" name="radioBtn" id="radioBtn2" value="B" onMouseDown="this.__chk = this.checked" onClick="if (this.__chk) this.checked = false"/> 
<input type="radio" name="radioBtn" id="radioBtn3" value="C" onMouseDown="this.__chk = this.checked" onClick="if (this.__chk) this.checked = false"/> 
+0

非常感謝。有用。 – Nomad

+0

onMouseDown =「this .__ chk這是什麼__chk? –

0

保持其單選按鈕被選中的記錄,這是不(可以用隱藏字段或數組完成),並設置選中/取消accordinally

0

讓您可以爲單選按鈕瀏覽器的默認行爲,並通過創建一個額外的「隱藏」單選按鈕,併爲它在模擬click事件實現切換效果你後用戶切換其中一個可見按鈕。在這個jsFiddle看到一個工作示例:http://jsfiddle.net/k73Nt/

0

這可能不是一個解決方案,它會進入本書的清潔,但我得到它的工作。

http://jsfiddle.net/C9At9/3/

HTML:

<input type="radio" name="radioBtn" id="radioBtn1" value="A" onmouseup="toggle(this);"/> 
<input type="radio" name="radioBtn" id="radioBtn2" value="A" onmouseup="toggle(this);" /> 
<input type="radio" name="radioBtn" id="radioBtn3" value="A" onmouseup="toggle(this);"/> 

的Javascript:

function toggle(radioBtn) 
{ 
    if(radioBtn.checked) 
    { 
    setTimeout("disableRadio('"+radioBtn.id+"')",10); 
    } else { 
    radioBtn.checked = true; 
    } 
} 

function disableRadio(radioId) { 
    el = window.document.getElementById(radioId); 
    el.checked = false; 
} 

你的代碼是行不通的,因爲JavaScript的二傳手得到由HTML點擊事件什麼的否決。我不知道如何以正確的方式解釋它,但延遲解決了你的問題。

希望這可以幫到你!

相關問題